简体   繁体   中英

How to Set an ActionListener to a JFormattedTextField?

I tried to add an ActionListener to a JFormattedTextField. It does not invoke the listener while text change or focus change:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

class ActionListenerExample extends JPanel {

    public static void main(String[] args) {

        JFrame f = new JFrame("Action Listener Example : ");
        JPanel anyBICPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 1, 1));
        anyBICPanel.setName("anyBICPanel");
        JLabel anyBICLbl = new JLabel("Any BIC");
        anyBICLbl.setName("anyBICLbl");
        anyBICPanel.add(anyBICLbl);
        JFormattedTextField anyBICTxt = new JFormattedTextField();
        anyBICTxt.setName("anyBICTxt");
        anyBICTxt.setColumns(30);
        anyBICPanel.add(anyBICTxt);
        anyBICTxt.addActionListener(anyBICActionListener);

        JTextField tf2 = new JTextField(5);
        anyBICPanel.add(tf2);

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(anyBICPanel);
        f.pack();
        f.setVisible(true);
    }
    public static ActionListener anyBICActionListener = new ActionListener() {

        public void actionPerformed(ActionEvent evnt) {
            String text = ((JFormattedTextField) evnt.getSource()).getText().toString();
            JOptionPane.showMessageDialog(null, "Text : " + text);
        }
    };
}

What is the right way to set an ActionListener to a JFormattedTextField?

It does not invoke the listener while text change or focus change:

Good as this means that the ActionListener is behaving appropriately as it should only be called when Enter is pressed. It looks like you want to use a different listener such as a FocusListener, or DocumentListener, or perhaps an InputVerifier.

Note that JFormattedTextField also has a setFocusLostBehavior(int behavior) method that allows you to specify what it should do when focus is lost and the data is corrupt.

Why do you have it as a static? Just add it like below.

anyBICTxt.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent evnt) {
            String text = ((JFormattedTextField) evnt.getSource()).getText().toString();
            JOptionPane.showMessageDialog(null, "Text : " + text);
     }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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