代码之家  ›  专栏  ›  技术社区  ›  Steve McLeod

为什么我必须按两次Enter键才能激活JDialog的默认按钮?

  •  1
  • Steve McLeod  · 技术社区  · 15 年前

    按回车键以使这发生。

    这是在Mac OS X 10.6和当前的Mac Java更新1.6.0\ U 20上实现的。

    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);
        }
    
    }
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   bragboy    15 年前

    添加此代码解决了问题,

    formattedTextField.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            dialog.dispose();
        }
    });
    
        2
  •  0
  •   3xCh1_23    13 年前

            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
        }
    
    推荐文章