在另一个JavaBean中设置绑定的JavaBean

时间:2014-04-01 06:51:54

标签: java user-interface netbeans javabeans

我在设置另一个bean的成员并正确更新的bean时遇到了问题。更具体地说,我有:

public class MyForm extends javax.swing.JFrame {
    MyBean aBean;
    JTextField aTextField;
    ....
    public MyBean getABean() { return aBean; }
    public void setABean(MyBean newBean) { 
        MyBean oldBean = aBean;
        aBean = newBean;
        propertyChangeSupport.firePropertyChange(PROP_MYBEAN, oldBean, aBean);
    }
    ...
    binding = Bindings.createAutoBinding(
        AutoBinding.UpdateStrategy.READ_WRITE,
        aBean, 
        ELProperty.create("${file.name}"),
        aTextField, 
        BeanProperty.create("text")
    );
    bindingGroup.addBinding(binding);
    ...
}

其中MyBeanFile成员,并有适当的getter广告设置者。我想要做的就是拥有它,以便我可以使用setter更改aBean并绑定任何更新以反映新aBean的值。

我可以看到这个问题;原始aBean绑定到TextField,并且在分配新的aBean时,没有“交换”。但是,看到问题并不意味着我有解决方案!

我目前的解决方案涉及一个中级班级。我MyFormMyMiddleManMyMiddleManMyBean。每当我想要更改MyBean时,都会调用MyMiddleMan中的setter并触发MyForm看到的相应事件。 MyForm的成员永远不会改变,因此它“有效”。

我的解决方法在很多层面都很糟糕。有更好的,最佳实践方式吗?我承认我不是豆专家,可能会遗漏一些明显的东西。我正在使用NetBeans IDE 8.0,如果这是相关的,并且想要使用构建器生成我的GUI。显然,我的实际代码比这个例子大得多,所以如果我每次都要开始添加额外的代码,那可能会很麻烦。

我在下面有一个工作示例来演示我的问题。由于豆需要公开,有三个文件; MyBean.java,MyMiddleMan.java和MyForm.java。它应该生成四个绑定的文本字段。第一个演示我可以毫无问题地更改成员的内容。第二个显示我的问题(我知道为什么它不起作用,只是没有如何解决它),第三个是无关紧要的,从教程中作为一个“健全性检查”,第四个是使用我的“MyMiddleMan “解决方法。

MyBean.java

package testpackage;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;

public class MyBean {

    private File file;

    public static final String PROP_FILE = "file";

    public MyBean() {
    }

    public MyBean(File file) {
        this.file = file;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        File oldFile = this.file;
        this.file = file;
        propertyChangeSupport.firePropertyChange(PROP_FILE, oldFile, file);
    }

    private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

    @Override
    public String toString() {
        return "MyBean{" + "file=" + file.getName() + '}';
    }

}

MyMiddleMan.java

package testpackage;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class MyMiddleMan {

    private MyBean myBean;

    public static final String PROP_MYBEAN = "myBean";

    /**
     * Get the value of myBean
     *
     * @return the value of myBean
     */
    public MyBean getMyBean() {
        return myBean;
    }

    /**
     * Set the value of myBean
     *
     * @param myBean new value of myBean
     */
    public void setMyBean(MyBean myBean) {
        MyBean oldMyBean = this.myBean;
        this.myBean = myBean;
        propertyChangeSupport.firePropertyChange(PROP_MYBEAN, oldMyBean, myBean);
    }

    private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    /**
     * Add PropertyChangeListener.
     *
     * @param listener
     */
    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    /**
     * Remove PropertyChangeListener.
     *
     * @param listener
     */
    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

}

MyForm.java 其中大部分是由NetBeans自动生成的。

package testpackage;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;

public class MyForm extends javax.swing.JFrame {

    private static final long serialVersionUID = -9151817428068627139L;

    public MyForm() {
        initComponents();
        myBean1.setFile(new File("test.txt"));
        setMyBean2(new MyBean(new File("test.txt")));
        myMiddleMan1.setMyBean(new MyBean(new File("test.txt")));

        System.out.println("MyBean1: " + myBean1);
        System.out.println("MyBean2: " + myBean2);
        System.out.println("MyMiddleMan.myBean: " + myMiddleMan1.getMyBean());
    }

    public static final String PROP_MYBEAN2 = "myBean2";

    /**
     * Get the value of myBean2
     *
     * @return the value of myBean2
     */
    public MyBean getMyBean2() {
        return myBean2;
    }

    /**
     * Set the value of myBean2
     *
     * @param myBean2 new value of myBean2
     */
    public void setMyBean2(MyBean myBean2) {
        MyBean oldMyBean2 = this.myBean2;
        this.myBean2 = myBean2;
        propertyChangeSupport.firePropertyChange(PROP_MYBEAN2, oldMyBean2, myBean2);
    }

    private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    /**
     * Add PropertyChangeListener.
     *
     * @param listener
     */
    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    /**
     * Remove PropertyChangeListener.
     *
     * @param listener
     */
    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        myBean1 = new testpackage.MyBean();
        myBean2 = new testpackage.MyBean();
        myMiddleMan1 = new testpackage.MyMiddleMan();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jSlider1 = new javax.swing.JSlider();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, myBean1, org.jdesktop.beansbinding.ELProperty.create("${file.name}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, jSlider1, org.jdesktop.beansbinding.ELProperty.create("${value}"), jTextField2, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, myBean2, org.jdesktop.beansbinding.ELProperty.create("${file.name}"), jTextField3, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, myMiddleMan1, org.jdesktop.beansbinding.ELProperty.create("${myBean.file.name}"), jTextField4, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel1.setText("Altering aBean");

        jLabel2.setText("Setting new aBean");

        jLabel3.setText("Slider (irrelevant)");

        jLabel4.setText("Using MyMiddleMan");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(79, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(190, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MyForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private testpackage.MyBean myBean1;
    private testpackage.MyBean myBean2;
    private testpackage.MyMiddleMan myMiddleMan1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:1)

我解决了。

我选择myBean作为来源并绑定到${file.name}

选择Form作为来源并绑定${myBean.file.name}

是有效的