简体   繁体   English

为什么JFormattedTextField不支持actionPerformed

[英]Why JFormattedTextField does not suppport actionPerformed

I have a JFormattedTextField in my form, and i wish that after entering value when user presses enters it should move to next field. 我的表单中有一个JFormattedTextField ,我希望在用户按下输入后输入值后,它应该移动到下一个字段。 But after my all tries I am failed to do so. 但经过我的努力,我没有这样做。 To achieve this I have attached an ActionListener to JFormattedTextField but pressing of Enter never trigger event. 为了实现这一点,我已经将一个ActionListener附加到JFormattedTextField但按Enter键从不触发事件。 Why? 为什么? can anybody help? 任何人都可以帮忙吗?

public class Test extends javax.swing.JFrame {

    /**
     * Creates new form Test
     */
    public Test() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        ftf = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        ftf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        ftf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ftfActionPerformed(evt);
            }
        });

        jLabel1.setText("JFormattedTextField Action Test");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ftf, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(167, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(ftf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(238, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void ftfActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        JOptionPane.showMessageDialog(this, "Enter Pressed");
    }                                   

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Test().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JFormattedTextField ftf;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

You need to add an Action : 您需要添加一个Action

Action action = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        //preform your action here.
    }
};


ftf.addActionListener( action );

And the action is executed when enter key is pressed. 当按下回车键时执行动作。

You can do it by either way. 你可以通过任何一种方式实现。

1. There is a simple trick for this. 1.有这个一个简单的一招。 After you constructed the frame with all it buttons do this: 用所有按钮构造框架后,执行以下操作:

frame.getRootPane().setDefaultButton(submitButton);

For each frame, you can set a default button that will automatically listen to the Enter key (and maybe some other event's I'm not aware of). 对于每个帧,您可以设置一个默认按钮,该按钮将自动侦听Enter键(可能还有其他一些我不知道的事件)。 When you hit enter in that frame, the ActionListeners their actionPerformed() method will be invoked. 当您在该帧中按Enter键时,将调用ActionListeners的actionPerformed()方法。

2. A JFormattedTextField was designed to use an ActionListener just like a JButton is. 2. JFormattedTextField被设计为像JButton一样使用ActionListener See the addActionListener() method of JFormattedTextField. 请参阅JFormattedTextField的addActionListener()方法。

For example: 例如:

Action action = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("some action");
    }
};

JFormattedTextField textField = new JFormattedTextField(10);
textField.addActionListener( action );

Now the event is fired when the Enter key is used. 现在,使用Enter键时会触发该事件。

Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button. 此外,即使您不想将按钮设置为默认按钮,您还可以使用按钮共享监听器。

JButton button = new JButton("Do Something");
button.addActionListener( action );

Note, this example uses an Action, which implements ActionListener because Action is a newer API with addition features. 注意,此示例使用Action,它实现ActionListener,因为Action是具有附加功能的较新API。 For example you could disable the Action which would disable the event for both the text field and the button. 例如,您可以禁用Action,它将禁用文本字段和按钮的事件。

Instead of ActionListener you can bind Enter key to JFormattedTextField and call AbstractAction when Enter is pressed: 您可以将Enter键绑定到JFormattedTextField而不是ActionListener ,并在按下Enter时调用AbstractAction

InputMap inputMap = ftf.getInputMap(JComponent.WHEN_FOCUSED);
        inputMap.put(KeyStroke.getKeyStroke((char) KeyEvent.VK_ENTER), "enterPressed");
        ftf.getActionMap().put("enterPressed", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("actionPerformed");
                ftfActionPerformed(e);
            }
        });

When JFormattedTextField is focused it will handle Enter key in actionPerformed method JFormattedTextField聚焦时,它将在actionPerformed方法中处理Enter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM