wannik
wannik

Reputation: 12696

Java beans binding in GUI

I created a User bean class and bind it to a JTextField. I'd like to update the textfield when a method setName of the bean is call. Here is the code:

package newpackage;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class User {

    private String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        propertyChangeSupport.firePropertyChange(null, null, null);
    }

    private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }
}

I use NetBeans to design a GUI. It works. But I was wondering whether it is a correct way to implement bean binding with a Swing component.

Upvotes: 0

Views: 441

Answers (1)

Puce
Puce

Reputation: 38122

Almost. Try something like this (untested):

public void setName(String name) {
       String oldName = this.name;
       this.name = name;
       propertyChangeSupport.firePropertyChange("name", oldName, name);
}

See the Javadoc.

Upvotes: 1

Related Questions