Change format for JFormattedTextField Dynamically in Java
Description
The following code shows how to change format for JFormattedTextField Dynamically.
Example
import java.awt.BorderLayout;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//from ww w .jav a 2 s.com
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.DateFormatter;
public class Main {
public static void main(final String args[]) throws ParseException {
JFrame frame = new JFrame("Formatted Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFormattedTextField f = new JFormattedTextField(new SimpleDateFormat("yyyy-M-d"));
f.setValue(new Date());
DateFormatter fmt = (DateFormatter) f.getFormatter();
fmt.setFormat(new SimpleDateFormat("d/M/yyyy"));
f.setValue(f.getValue());
frame.add(f, 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 »