为什么我必须为此 JFormattedTextField 按两次 Enter 才能激活 JDialog 的默认按钮?
在下面的代码示例中,如果用户更改 JFormattedTextField 的内容然后按 Enter,则该对话框应该表现得就像按下“确定”按钮一样。但需要按两次 Enter 键才能发生此情况。
普通的 JTextField 总是按照我的预期运行 - 更改文本然后按 Enter 键会立即激活“确定”按钮。
此功能适用于 Mac OS X 10.6 以及当前的 Mac Java 更新 1.6.0_20。
这是一个解决方法吗?这是 Mac 特有的问题吗?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.text.NumberFormat;
import java.text.ParseException;
public class ScratchSpace {
public static void main(final String[] args) throws ParseException {
final JDialog dialog = new JDialog((Frame) null, "Test", true);
dialog.setLayout(new FlowLayout());
dialog.add(new JLabel("text field: "));
dialog.add(new JTextField(20));
dialog.add(new JLabel("formatted text field: "));
final JFormattedTextField formattedTextField = new JFormattedTextField(NumberFormat.getIntegerInstance());
formattedTextField.setValue(42);
formattedTextField.setColumns(20);
dialog.add(formattedTextField);
final JButton okButton = new JButton(new AbstractAction("OK") {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(okButton);
dialog.getRootPane().setDefaultButton(okButton);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}
In the code sample below, if a user changes the contents of the JFormattedTextField then presses Enter, the dialog is supposed to act as if the OK button is pressed. But it takes two presses of Enter for this to happen.
The plain vanilla JTextField always acts as I would expect - changing the text then pressing Enter activates the OK button straight away.
This in on Mac OS X 10.6 with the current Mac Java update 1.6.0_20.
Is this a work-around? Is this a Mac specific problem?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.text.NumberFormat;
import java.text.ParseException;
public class ScratchSpace {
public static void main(final String[] args) throws ParseException {
final JDialog dialog = new JDialog((Frame) null, "Test", true);
dialog.setLayout(new FlowLayout());
dialog.add(new JLabel("text field: "));
dialog.add(new JTextField(20));
dialog.add(new JLabel("formatted text field: "));
final JFormattedTextField formattedTextField = new JFormattedTextField(NumberFormat.getIntegerInstance());
formattedTextField.setValue(42);
formattedTextField.setColumns(20);
dialog.add(formattedTextField);
final JButton okButton = new JButton(new AbstractAction("OK") {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(okButton);
dialog.getRootPane().setDefaultButton(okButton);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加这段代码解决了问题,
Adding this code solved the problem,
这并没有解决我的问题。然而,问题的解决方案对我来说似乎要简单得多:
This did not solve my problem. However, it seemed that the problem solution was much simpler for me: