簡體   English   中英

為什么JFormattedTextField不支持actionPerformed

[英]Why JFormattedTextField does not suppport actionPerformed

我的表單中有一個JFormattedTextField ,我希望在用戶按下輸入后輸入值后,它應該移動到下一個字段。 但經過我的努力,我沒有這樣做。 為了實現這一點,我已經將一個ActionListener附加到JFormattedTextField但按Enter鍵從不觸發事件。 為什么? 任何人都可以幫忙嗎?

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                   
}

您需要添加一個Action

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


ftf.addActionListener( action );

當按下回車鍵時執行動作。

你可以通過任何一種方式實現。

1.有這個一個簡單的一招。 用所有按鈕構造框架后,執行以下操作:

frame.getRootPane().setDefaultButton(submitButton);

對於每個幀,您可以設置一個默認按鈕,該按鈕將自動偵聽Enter鍵(可能還有其他一些我不知道的事件)。 當您在該幀中按Enter鍵時,將調用ActionListeners的actionPerformed()方法。

2. JFormattedTextField被設計為像JButton一樣使用ActionListener 請參閱JFormattedTextField的addActionListener()方法。

例如:

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

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

現在,使用Enter鍵時會觸發該事件。

此外,即使您不想將按鈕設置為默認按鈕,您還可以使用按鈕共享監聽器。

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

注意,此示例使用Action,它實現ActionListener,因為Action是具有附加功能的較新API。 例如,您可以禁用Action,它將禁用文本字段和按鈕的事件。

您可以將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);
            }
        });

JFormattedTextField聚焦時,它將在actionPerformed方法中處理Enter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM