Contact to javax.beans.binding

This little example will show you how to bind a JTextField to a name property of a Person with Beans Binding (JSR-295). First the Person:

package com.tutego.binding;

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

public class Person
{
private PropertyChangeSupport pcs = new PropertyChangeSupport( this );

private String name = "";

public void addPropertyChangeListener( PropertyChangeListener x )
{
pcs.addPropertyChangeListener( x );
}

public void removePropertyChangeListener( PropertyChangeListener x )
{
pcs.removePropertyChangeListener( x );
}

public String getName()
{
return name;
}

public void setName( String name )
{
String old = getName();
this.name = name;
pcs.firePropertyChange( "name", old, getName() );

System.out.println( "Changed name!" );
}
}

The code for the JavaBean Person is a litte bit cumbersome because of the PropertyChangeListener who will notify the Binding Framework if the model change.

package com.tutego.binding;

import javax.beans.binding.BindingContext;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class BindingDemo
{
public static void main( String[] args )
{
Person p = new Person();

JTextField tf = new JTextField();

BindingContext bindingContext = new BindingContext();
bindingContext.addBinding( p, "${name}", tf, "text" );
bindingContext.bind();


JFrame f = new JFrame();
f.add( tf );
f.pack();
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setVisible( true );

p.setName( "Christian Ullenboom" );
}
}


Swing on the other side will although notify the model if the user type text in the text field and press Return. This will change the model.

2 Antwort(en) auf ›Contact to javax.beans.binding‹

  1. # Anonymous Anonym

    Ah, jetzt verstehe ich, wie das mit dem Model/View/Presenter gemeint ist. :-)
    Ja, das sieht auf alle Fälle sauberer aus.
    Das Binding in NetBeans finde ich trotzdem noch in Ordnung.

    Gruß, Philip  

  2. # Blogger Josch

    Hi!

    Building setter-Methods with Beans and PropertyChangeSupport is a hard work for lazy programmers. But you can write a setter in a single line:

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

    best regards, josh.  

Kommentar veröffentlichen