【问题标题】:java beansbinding JButton.enabledjava beansbinding JButton.enabled
【发布时间】:2013-07-29 17:34:36
【问题描述】:

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

所以我尝试创建一个 ELBinding(它具有条件支持,例如 ${myProperty > 50} 返回一个布尔值,该布尔值持有该表达式是否为真。

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

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

非常感谢任何提示,因为我发现 ELProperties 的文档记录不充分。

【问题讨论】:

    标签: java swing jbutton propertychangelistener beans-binding


    【解决方案1】:

    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;
        }
    }
    

    【讨论】: