Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JFormattedTextField and nulls 1

Status
Not open for further replies.

kmcculler

Programmer
Jul 5, 2000
81
0
0
US
Hey, anybody know how to get a JFormattedTextField to accept null as a valid value? I'm using the default DateFormatter as my format and I want either a valid date or null to be accepted, but nothing else....

Kris McCuller
 
Interesting question. I haven't used the JFormattedtextField yet so the following may not be the best way, but...

If you subclass the AbstractFormat you could modify the format parsing to allow your behaviour.
Code:
public class MyFormat extends JFormattedTextField.AbstractFormatter {
  private SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
		
  public Object stringToValue(String text) throws ParseException {
    if ( text.length() == 0 ) return null;
    return format.parse(text);
  }

  public String valueToString(Object value) throws ParseException {
    if ( value == null ) return "";
    return format.format(value);
  }	
}

You would then use this when creating a JFormattedtextField which will then allow blanks.
Code:
    JFormattedTextField ftf = new JFormattedTextField(new MyFormat());

I gave this a quick try and it seems to work. I'd be interested to hear if there is a better way though.

Tim
 
Not having used the the JFormattedTextField, I am only offering a guess...

Either extend the JForrmattedTextField to overwrite the the invalidEdit and isEditVaild OR extend the DateFormatter to accept null as a valid date...
 
Subclassing the abstractformatter seemed to do the trick. Thanks. I can hardly belive I overlooked such a simple fix to my prob, but then again I haven't worked with the formatters or JFormattedTextField before either.

Kris McCuller
 
Subclassing the abstractformatter seemed to do the trick. Thanks. I can hardly belive I overlooked such a simple fix to my prob, but then again 0I haven't worked with the formatters or JFormattedTextField before either.

Kris McCuller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top