Retrieve a date with Java Swing
Let's get a date

Retrieve a date with Java Swing

This article provides a simple way to retrieve a date in a GUI using Swing JFormattedTextField object.

Let's get a date

The object "JFormattedTextField" can retrieve the text entered by the user as a JTextField but also check that the user is using the desired format. This object can be used to retrieve data in a specific format as a phone number or social security number.
Here is a small example: We want to obtain an entry field that displays the date in a nice format when it is not selected, but also easily editable when it has focus.
//we choose the wanted date pattern
DateFormatter dateFormatter=new DateFormatter(new SimpleDateFormat("dd/MM/yyyy"));
//the javadoc new DefaultFormatterFactory(defaultFormat, displayFormat, editFormat)
DefaultFormatterFactory dateFormatterFactory =new DefaultFormatterFactory(dateFormatter,
 new DateFormatter(),
JFormattedTextField dateField = new JFormattedTextField(dateFormatterFactory);
p.add(new JLabel("Date: "));
//initialize with now
dateField.setValue(new Date());
//done :)
Be The First To Comment.

Add a comment:

You can use these HTML tags: <br><a><i><b>