swingdesktop-applicationbeans-binding

How to bind a component to more beansbinding classes


Any one know how to bind one swing JComponent to two BeansBinding classes(Specially with Netbeans IDE)? Also how to bind a variable in JFrame to a beanbinding class's property?


Solution

  • A) Hmm ... still not sure what exactly you want to achieve: build a binding chain, maybe? Something like

    bean."name" <--> textField."text" --> otherBean.logger

        BindingGroup context = new BindingGroup();
        context.addBinding(Bindings.createAutoBinding(UpdateStrategy.READ_WRITE,
                bean, BeanProperty.create("name"), 
                field, BeanProperty.create("text"))); 
        context.addBinding(Bindings.createAutoBinding(UpdateStrategy.READ,
                field, BeanProperty.create("text"), 
                otherBean, BeanProperty.create("logger"))); 
    

    B) Beansbinding is all about binding properties not fields (aka: variables). So whatever you want to bind needs a getter and (maybe a setter, depends on your requirements) and must fire notification on change. Then do the binding just as always ..

    public MyFrame extends JFrame {
        private int attempts;
    
        public int getAttempts() {
            return attempts;
        } 
    
        private void incrementAttempts() {
            int old = getAttempts();
            attempts++;
            firePropertyChange("attempts", old, getAttempts()); 
        }
    
        private void bind() {
        BindingGroup context = new BindingGroup();
        context.addBinding(Bindings.createAutoBinding(UpdateStrategy.READ,
                this, BeanProperty.create("attempts"), 
                label, BeanProperty.create("text"))); 
    
        }
    }