java什么是适配器类?作用是什么?,JavaBeans属性适配器如何工作?

What I'm trying to do works fine if I follow the JavaFX property definition described here.

Now, instead, I want to define properties from Java Beans objects using Java Beans Property Adapter. Since there is no documentation I can't figure out how it works.

Suppose I have a simple POJO class:

public class Person {

private String name;

public String getName() {

return name;

}

public void setName( String name ) {

this.name = name;

}

}

and a PersonProperty:

public class PersonProperty {

private Person person = new Person();

private JavaBeanStringProperty name;

public PersonProperty() throws NoSuchMethodException {

name = JavaBeanStringPropertyBuilder.create().bean( person ).name( "name" ).build();

}

public Person getPerson() {

return person;

}

public void setPerson( Person person ) {

this.person = person;

}

public JavaBeanStringProperty nameProperty() {

return name;

}

}

and finally a test:

public void personTest() throws NoSuchMethodException {

PersonProperty pp = new PersonProperty();

pp.getPerson().setName( "A" );

pp.getPerson().setName( "B" );

pp.nameProperty().addListener( new ChangeListener() {

@Override

public void changed( ObservableValue extends String> ov, String t, String t1 ) {

System.out.println( "from " + t + " to " + t1 );

}

} );

pp.getPerson().setName( "C" );

pp.getPerson().setName( "D" );

}

I'm expecting to see:

from B to C

from C to D

Instead nothing appears.

If I add pp.nameProperty().set("E") at the end of personTest I get from B to E

解决方案

I think the issue here is that Person is indeed a POJO, but not a JavaBean: It is missing the hooks for PropertyChangeListeners. Java will not magically know when Person#name changes. Instead, the JavaFX adapter will look for a way to add a PropertyChangeListener and listen to events for a property called 'name'. If you add a PropertyChangeSupport instance to your Person class it will work as expected:

public class Person {

private String name;

private PropertyChangeSupport _changeSupport;

public Person() {

_changeSupport = new PropertyChangeSupport(this);

}

public String getName() {

return name;

}

public void setName( String name ) {

final String prev = this.name;

this.name = name;

_changeSupport.firePropertyChange("name", prev, name);

}

public void addPropertyChangeListener(final PropertyChangeListener listener) {

_changeSupport.addPropertyChangeListener(listener);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值