In the example code, pressing the button calls the bean's setName() method, firing a propertyChangeEvent from the bean, but the JTextField doesn't respond. My guess is that nobody's listening to the fired event, and I'm not sure who should (the JTextField? Or some component of the Binding apparatus?)
Any help you can provide would be greatly appreciated.
Thanks,
Ed
- Code: Select all
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.beansbinding.Bindings;
import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import javax.swing.JButton;
public class BindingTest extends JPanel {
protected JTextField textField;
protected Model model = new Model();
public BindingTest() {
JButton button = new JButton("New button");
add(button);
textField = new JTextField();
add(textField);
textField.setColumns(10);
initDataBindings();
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
model.setName("foo");
}
});
}
protected void initDataBindings() {
BeanProperty<Model, String> modelBeanProperty = BeanProperty.create("name");
BeanProperty<JTextField, String> jTextFieldBeanProperty = BeanProperty.create("text");
AutoBinding<Model, String, JTextField, String> autoBinding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, model, modelBeanProperty, textField, jTextFieldBeanProperty);
autoBinding.bind();
}
public static class Model {
protected PropertyChangeSupport support = new PropertyChangeSupport(this);
protected String name;
public String getName() {
return name;
}
public void setName(String newName) {
String oldName = this.name;
this.name = newName;
System.out.println("setName called: " + newName);
support.firePropertyChange(new PropertyChangeEvent(this, "name", oldName, newName));
}
public void addPropertyChangeListener(PropertyChangeListener l){
support.addPropertyChangeListener(l);
}
}
public static void main(String[] args){
BindingTest view = new BindingTest();
JFrame frame = new JFrame();
frame.getContentPane().add(view, BorderLayout.CENTER);
frame.setMinimumSize(new Dimension(500,500));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}