检查Java中的布尔值是否已更改

检查Java中的布尔值是否已更改,java,class,boolean,actionlistener,Java,Class,Boolean,Actionlistener,我有一个布局和一个按钮的类。我想知道是否有一个内置的方法或功能,我可以检测出布尔值是否在函数中发生了变化。我可以用一堆其他的布尔人来做,但我正在寻找一种更优雅的方式。我相信这与“观察者”有关,但我不能完全确定 该守则的简化版本如下: Class checker{ boolean test1 = true; boolean test2 = true; checker(){ checkNow.addActionListener(new 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?

}
}}); 

}
[是否]有一个内置的方法或功能,可以检测函数中的布尔值是否已更改

您可以通过使用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
    }
}
用调用
setTest1
setTest2
替换这些变量的所有赋值,以可靠地检测
test1
test2
中的更改

[是否]有一个内置的方法或功能,可以检测函数中的布尔值是否已更改

您可以通过使用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
    }
}
用调用
setTest1
setTest2
替换这些变量的所有赋值,以可靠地检测
test1
test2
中的更改,使布尔值私有化
2) 通过getter和setter访问它们
3) 在setter中:“if(this.val!=newVal)notify()”

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

一个选项(可能有些过分)将用于对
test1
test2
的值的更改感兴趣的组件,实现
PropertyChangeListener
并注册以在这些属性的值更改时侦听

这是一本书

一个选项(可能有些过分)是针对那些对
test1
test2
值的更改感兴趣的组件,实现一个
PropertyChangeListener
并在这些属性的值更改时注册以侦听


这是一本书

谢谢,我在做一件更复杂的事,多个布尔汉克,我对多个Boolean做了更复杂的事情除了DasbLinkedLight的答案外,您还可以使用PropertyChangeListener方法在bean的属性发生更改时通知其他组件。当bean的属性发生更改时,您还可以使用PropertyChangeListener方法和DasbLinkedLight的答案通知其他组件你的豆子变了。