How can I setup a JTextField to only accept valid dates?

Joe Walker

It depends what you mean by 'accept'.

You can validate the choice at three times:

  1. As the user types characters
  2. After the user is done with the field
  3. After the user is done with the GUI

Validating as the user types

To see if the current text makes up a valid Date, register a DocumentListener with the JTextField's document and then use a SimpleDateFormat to parse the date and provide user feedback in some way, perhaps by changing the color of the JTextField.

Validating when done with the field

You need to register listeners for:

  1. Focus change (leaving the JTextField)
  2. Pressing enter (ActionListener)
  3. Finishing the GUI (whatever action the user takes, like pressing a "done" button)

On any of the above events, perform the data validation.

Validating when done with the GUI

In this case, only perform your validation when the user presses "Done" or whatever action ends the user interaction with the GUI.

Alternative

Another alternative is to find a Calendar widget from somewhere. There are several available on the net, and some are free.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact