Using JFormattedTextField with strict SimpleDateFormat

Hello, here I'm going to show you how to use JFormattedTextField with a strict SimpleDateFormat in a tiny program.


import javax.swing.*;
import java.awt.*;
import java.text.*;
class JFormattedFieldExample extends JFrame
{
JFormattedTextField t;

public JFormattedFieldExample()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("JFormattedField Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
SimpleDateFormat s=new SimpleDateFormat("dd/MM/yyyy");
// Make it strict, so that it doesn't allow
// some conditions like, if month > 12
// day > 31 etc.
s.setLenient(false);
t=new JFormattedTextField(s);
t.setColumns(20);
try
{
t.setValue(s.parse("01/01/1996"));
}catch(Exception e){}
add(t);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[])
{
new JFormattedFieldExample();
}
}

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)

“Try and fail, but don't fail to try.” - Stephen Kaggwa

No comments: