1

我有一个带有布局和一个按钮的类。我想知道是否有内置的方法或功能可以检测函数中的布尔值是否发生了变化。我可以用一堆其他布尔值来做到这一点,但我正在寻找一种更优雅的方式。我相信这与“观察者”有关,但并不完全确定。

代码的简化版本如下:

Class checker{

 boolean test1 = true;
 boolean test2 = true;

checker(){

checkNow.addActionListener(new ActionListener() {            
public void actionPerformed(ActionEvent e)
{   

//code to manage, and possibly change the value of the booleans test1 and test2.
//is there any built in function in java where i can test to see if the value of the booleans was changed in this actionListener function?

}
}}); 

}
4

3 回答 3

6

[是否] 有一个内置的方法或功能,我可以检测函数中的布尔值是否发生了变化?

您可以通过boolean使用 setter 封装对变量的访问来做到这一点:

private boolean test1 = true;
private boolean test2 = true;

private void setTest1(boolean newTest1) {
    if (newTest1 != test1) {
        // Do something
    }
}

private void setTest2(boolean newTest2) {
    if (newTest2 != test2) {
        // Do something
    }
}

用 和 的调用替换这些变量的所有分配,setTest1以可靠地检测和setTest2的变化。test1test2

于 2012-10-04T02:12:35.420 回答
1

1) 将布尔值设为私有
2) 通过 getter 和 setter 访问它们
3) 在 setter 中:'if (this.val!=newVal) notify()'

于 2012-10-04T02:14:45.580 回答
0

一个选项(这可能是矫枉过正)将是组件对值的更改感兴趣test1test2实现 aPropertyChangeListener和 register 以侦听这些属性的值何时更改。

这是一个教程

于 2012-10-04T03:29:26.817 回答