以下のコード サンプルでは、ユーザーが JFormattedTextField の内容を変更して Enter キーを押すと、ダイアログは [OK] ボタンが押されたように動作するはずです。ただし、これを行うには、Enter キーを2 回押す必要があります。
普通の普通の JTextField は常に期待どおりに機能します。テキストを変更してから Enter キーを押すと、すぐに [OK] ボタンがアクティブになります。
これは、最新の Mac Java アップデート 1.6.0_20 を適用した Mac OS X 10.6 に対応しています。
これは回避策ですか? これは 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);
}
}