1

以下のコード サンプルでは、​​ユーザーが 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);
    }

}
4

2 に答える 2

1

このコードを追加すると問題が解決し、

formattedTextField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        dialog.dispose();
    }
});
于 2010-09-16T11:17:04.650 に答える
0

これは私の問題を解決しませんでした。ただし、問題の解決策は私にとってはるかに簡単だったようです。

        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
   add(jTextField1);          //this reacts after the "ENTER" gets pressed
   jButton1.doClick();        //this activates the button
   jTextField1.setText("");   //this removes the text from a text-field
  jTextField1.grabFocus();    //this sets a cursor within a text-field
    }
于 2012-11-12T16:30:35.750 に答える