Add action listener for JFormattedTextField in Java
Description
The following code shows how to add action listener for JFormattedTextField.
Example
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.Format;
import java.text.NumberFormat;
/*from w w w . j ava 2 s .c om*/
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
public static void main(final String args[]) {
JFrame frame = new JFrame("Formatted Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Format general = NumberFormat.getInstance();
JFormattedTextField input = new JFormattedTextField(general);
input.setValue(2424.50);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JFormattedTextField source = (JFormattedTextField) actionEvent.getSource();
Object value = source.getValue();
System.out.println("Class: " + value.getClass());
System.out.println("Value: " + value);
}
};
input.addActionListener(actionListener);
frame.add(input, BorderLayout.NORTH);
frame.add(new JTextField(), BorderLayout.SOUTH);
frame.setSize(250, 100);
frame.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »