tags:

views:

91

answers:

3

Hi,

How can I link a variable and a text box in the simplest possible way?

I.e. If the user changes the text box contents the variable changes and if the program changes the variable the text in the text box changes.

N.B. I'm using the swing and awt libraries.

Thanks in advance.

+1  A: 

put your variable in an Observable wrapper. It will tell the JTextfield about the changes.

add a DocumentListener to the field.getDocument() to tell your variable that its value should change.

Pierre
A: 

I would simply add an ActionListener to the JTextField to listen to changes. When it's time to update the field, make changes to the JTextField and be prepared to ignore the events it fires off as a result.

The other option is to edit the field's Document directly, and add a DocumentListener to listen for changes. I find working with Documents to be more complex than needed, however.

Jason Nichols
+1  A: 

If you find yourself doing lots of custom UI/Bean binding, consider JGoodies Binding.

Using Observable or a DocumentListener is ok.

For more advanced stuff, you may want to look at PropertyEditor, BeanDescriptor, BeanInfo and Customizer classes/interfaces.

John Doe