Illustration einer tropischen Insel mit Palmen und einem hohen Berg

Java Blog für Programmierer

Contact to javax.beans.binding

· Christian Ullenboom

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.

Kategorien: Allgemein

← Alle Beiträge