有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在netbeans中的JButton上使用Enabled属性

我试图用默认的CRUD数据库模板设置一个类似于“保存”按钮的按钮(只有在变量为true时,该按钮才会激活)。我查看了“保存”按钮的代码,发现我需要:

  1. 与之链接的变量(在他们的情况下需要保存)
  2. 要运行的操作

我在另一个按钮上重新创建了这两个按钮,但它永远无法启用。我在另外两个按钮上有打印语句,用来设置我的按钮链接到的变量为true和false,这样我就可以看到值在变化。 我是否错过了一些关键的步骤?这似乎应该是相当直截了当的

还有一件事,如果我在构造函数中将变量手动更改为true,然后运行应用程序,它会启用按钮,而false会禁用它,这样部分就工作了,而不是更改

如果有任何帮助,我将不胜感激,因为我在过去的几个小时里一直在努力,但还是无法找到答案

谢谢


共 (1) 个答案

  1. # 1 楼答案

    需要以某种方式监视变量或“属性”,可能是通过使用PropertyChangeSupport对象,并允许其他对象向其添加PropertyChangeListener,使其成为“bound property”。Swing应用程序有一个特殊的版本,负责Swing事件线程SwingPropertyChangeSupport,您可能希望使用它

    编辑
    你问

    Thanks for the reply, i assume that would be what firePropertyChange("saveNeeded", !saveNeeded, saveNeeded); is doing but waht is this doing? does this just notify the program or do i need to catch an handle this somewhere. This is based off the pre generated code so im not sure if it added something in the background.

    保存监视变量的类需要一个私有的SwingPropertyChangeSupport字段。您可以给它一个公共addPropertyChangeListener方法,允许其他类监听它的绑定属性,类似这样(如果属性是字符串):

    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.event.SwingPropertyChangeSupport;
    
    public class Foo {
       public static final String MY_BOUND_PROPERTY = "My Bound Property";
       private SwingPropertyChangeSupport spcSupport = new SwingPropertyChangeSupport(
             this);
       private String myBoundProperty;
    
       public void addPropertyChangeListener(PropertyChangeListener listener) {
          spcSupport.addPropertyChangeListener(listener);
       }
    
       public void removePropertyChangeListener(PropertyChangeListener listener) {
          spcSupport.removePropertyChangeListener(listener);
       }
    
       public String getMyBoundProperty() {
          return myBoundProperty;
       }
    
       public void setMyBoundProperty(String myBoundProperty) {
          Object oldValue = this.myBoundProperty;
          Object newValue = myBoundProperty;
    
          this.myBoundProperty = myBoundProperty;
          PropertyChangeEvent pcEvent = new PropertyChangeEvent(this,
                MY_BOUND_PROPERTY, oldValue, newValue);
          spcSupport.firePropertyChange(pcEvent);
       }
    
    }
    

    然后,任何想要监听更改的类只需将PropertyChangeListener添加到该类的对象中,并根据需要响应更改