1

在下面的代码示例中,如果用户更改了 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);
    }

}
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 回答