检查Java中是否更改了boolean

时间:2012-10-04 02:05:27

标签: java class boolean actionlistener

我有一个带有布局和单个按钮的课程。我想知道是否有内置的方法或功能,我可以检测功能中的布尔值是否已更改。我可以用一堆其他布尔值来做,但是正在寻找一种更优雅的方式。我认为它与“观察者”有关,但并不完全确定。

代码的简化版本如下:

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?

}
}}); 

}

3 个答案:

答案 0 :(得分:6)

  

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

您可以使用setter封装对boolean变量的访问权限来执行此操作:

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
    }
}

使用setTest1setTest2的调用替换这些变量的所有分配,以便可靠地检测test1test2中的更改。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

一个选项(可能是过度杀伤)将是对test1test2值的变化感兴趣的组件实现PropertyChangeListener并注册以监听何时这些属性的值会发生变化。

这是tutorial

相关问题