在下面的代码示例中,如果用户更改了 JFormattedTextField 的内容然后按 Enter,则该对话框应该就像按下 OK 按钮一样。但这需要按两次Enter 才能发生。
普通的 JTextField 总是像我期望的那样工作——更改文本然后按 Enter 会立即激活 OK 按钮。
这适用于 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);
}
}