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

标签 java swing netbeans jbutton

我正在尝试使用默认 CRUD 数据库模板设置一个类似于保存按钮的按钮(其中该按钮仅在变量为 true 时才变为 Activity 状态)。我查看了保存按钮的代码并确定了我需要的:

  1. 将其链接到的变量(在其情况下需要 saveNeeded)
  2. 要运行的操作

我已经在另一个按钮上重新创建了这两个按钮,但它永远不会被启用。我在另外 2 个按钮上有打印语句,我用来设置变量,我将按钮链接到 true 和 false,这样我就可以看到值正在变化。 我是否缺少一些关键步骤?这看起来应该是相当简单的。

另一件事,如果我在构造函数中手动将变量更改为 true 并运行应用程序,它将启用该按钮,而 false 将禁用它,以便该部分正常工作,而不是更改。

任何帮助将不胜感激,因为我在过去的几个小时里一直在尝试但无法弄清楚

谢谢

最佳答案

需要以某种方式监视变量或“属性”,也许可以通过使用 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.

保存监视变量的类需要一个私有(private) SwingPropertyChangeSupport 字段。您可以为其提供一个公共(public) addPropertyChangeListener 方法,在该方法中您可以允许其他类监听其绑定(bind)属性,如下所示(如果该属性是字符串):

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 添加到此类的对象,并根据需要响应更改。

关于java - 在 netbeans 中的 JButton 上使用 Enabled 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8347777/

相关文章:

java - 在docx4j-Java中设置A5页面大小

java - 在 netbeans 中为 Maven 项目设置自定义运行时类路径

java - 当单元测试覆盖率低于多模块项目中预先配置的限制时,maven 构建失败

java - 如何对集合中的两个不同对象进行排序?

java - Hybris 中的自定义产品 URL 解析器

java - 将 getter/setter 作为方法引用传递

java - 我正在尝试使用 GUI 使用 Java 创建 BMI 计算器,但收到语法错误

java - 在用户拖动鼠标时收听 JFrame 调整大小事件?

java - 将图标添加到 JList 项目

java - JPA 中两个表的 "Object comparisons can only be used with OneToOneMappings"