当(表单)包含JFormattedTextField
时,我遇到了使用表单默认按钮的问题。 在具有此类字段的表单上,如果它恰好有焦点(并且已被更改),则必须按OK 两次以获得默认按钮“已按下”。我想我知道它为什么会发生 - 这是因为第一次输入在提交处理中消耗。如何使JFormattedTextField在默认按钮的窗体上正常运行?
我也能够做一个解决方法 - 如果你改变Formatter
在每一个有效的编辑提交,那么你会得到正确的行为,但这a)强制你指定格式化程序explicilty,和b)不可能恢复到'旧'值(例如使用Escape或编程方式)。下面
代码演示了:当你在上面运行现场提交每个编辑和单作品则(但不能恢复),在底部字段允许将恢复,但需要进入,如果编辑。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.DateFormatter;
public class ExFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExFrame frame = new ExFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ExFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JFormattedTextField ff_1, ff_2;
//ff_1 has modified behavior of commit on each (valid) edit
DateFormatter f=new DateFormatter();
f.setCommitsOnValidEdit(true);
ff_1 = new JFormattedTextField(f);
ff_1.setValue(new Date());
//ff_2 has default behavior
ff_2 = new JFormattedTextField(new Date());
contentPane.add(ff_1, BorderLayout.NORTH);
contentPane.add(ff_2, BorderLayout.SOUTH);
JButton btnDefault = new JButton("I am default button");
contentPane.add(btnDefault, BorderLayout.CENTER);
getRootPane().setDefaultButton(btnDefault);
}
}
所以现在的问题是:有没有办法让JFormattedTextField
都提交上输入(所以输入是验证,但只有一次),如果成功地验证,激活默认按钮(单按)?
感谢挖掘出来! (显然,工作答案) – wmz 2012-08-15 11:32:18