java beansbinding JButton.enabled

问题描述 投票:1回答:1

我在Netbeans 7.3中使用jdesktop的beanbinding库。我有一个非常具体的问题。如果另一个bean的任何属性不为null,我想启用JButton,如果它为null则禁用。

所以我尝试创建一个ELBinding(它有像${myProperty > 50}这样的条件支持,返回一个布尔值,保存这个表达式是否为真。

但在我的场合,我无法弄清楚(也没有在互联网上找到)如何写下这个条件。如果我有一个属性更改的事件监听器,我会写这样的东西(在一些PropertyChangeListener实例的抽象方法中):

if (propertyChangeEvent.getNewValue() == null) {
    button.setEnabled(false);
} else {
    button.setEnabled(true);
}

非常感谢任何提示,因为我发现Properties很难记录。

java swing jbutton propertychangelistener beans-binding
1个回答
2
投票

worksforme,请参阅下面的示例。

但是:通常启动管理应该由bean本身处理(与在运行中这样做) - 在设计良好的分离世界中,只有bean本身应该拥有必要的所有知识。

一些代码:

final Person person = new Person();
// enablement binding with ad-hoc decision in view
Action action = new AbstractAction("Add year") {

    public void actionPerformed(ActionEvent e) {
        person.setAge(person.getAge() + 1);

    }
};
JButton button = new JButton(action);
Binding enable = Bindings.createAutoBinding(UpdateStrategy.READ, 
        person, ELProperty.create("${age < 6}"),
        button, BeanProperty.create("enabled"));
enable.bind();
// enablement binding to a bean property
Action increment = new AbstractAction("Increment year") {

    public void actionPerformed(ActionEvent e) {
        person.incrementAge();
    }
};
JButton incrementButton = new JButton(increment);
Binding incrementable = Bindings.createAutoBinding(UpdateStrategy.READ, 
        person, BeanProperty.create("incrementable"),
        incrementButton, BeanProperty.create("enabled"));
incrementable.bind();
JSlider age = new JSlider(0, 10, 0);
Binding binding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, 
        person, BeanProperty.create("age"),
        age, BeanProperty.create("value"));
binding.bind();

// the bean
public static class Person extends AbstractBean {
    private int age;
    private int max;
    public Person() { 
        max = 6;
    }

    public void incrementAge() {
        setAge(getAge() + 1);
    }

    public boolean isIncrementable() {
        return getAge() < max;
    }

    public void setAge(int age) {
        boolean incrementable = isIncrementable();
        int old = getAge();
        this.age = age;
        firePropertyChange("age", old, getAge());
        firePropertyChange("incrementable", incrementable, isIncrementable());
    }

    public int getAge() {
        return age;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.