tags:

views:

1167

answers:

4

I have a text field which is bound with Integer variable, so when user enters number into this field, binding mechanism automatically converts text into Integer and sets this value into var. Problem is, since user types text into text field, that binding mechanism is converting only values, and if user types some letters into it, binding would not activate because there is no legal value inside text field. What I would need in such situation, binding has to trigger change with null value, so I have null in my Integer var.

So, if user would left this field empty or something that is not number, binding will have to trigger null value propagation; not to ignore event... How could I do this without propgramming events on text field?

Is java binding capable for changing its default behaviour?

A: 

Besides altering the behaviour of the binding mechanism, you could put a Formatter into the TextField that only accepts numbers. You need to extend javax.swing.text.DefaultFormatter for this. And you would then use a JFormattedTextField instead of a normal JTextField.

The result would be that you only get valid input in your textfield and you don't have to make anything out of incorrect values.

boutta
well, that would work until user deletes last character in text field, Integer then would stay in last legal state, would not be null
+1  A: 

What you need is JFormattedTextField and NumberFormat.

Zarkonnen
+1  A: 

Swing support for constrained text input is appalling. JFormattedTextField will give you an utterly miserable user experience. As with most interesting Swing work, ignore the JComponent and go for the model. In this case Document, in particular DocumentFilter.

As it happens I have a simple Swing application that uses text fields constrained to integers that I prepared earlier. Description. Source (in particular see createNumberDocument ).

Tom Hawtin - tackline
A: 

well, lets suppose this problem with letters showing in text field is irrelevant, will be solved with JFormattedTextField...

The real problem in this situation is that when user clears last digit in text field; binding mechanism catches NumberFormatException during binding process (while trying to convert JTextField.getText() which now .equals("") to Number ) and stops with further propagation of event.

What I need in this situation, for binding mechanism to continue with event, just Number object will be null, or something default.. is that possible?