gpt4 book ai didi

java - 检查 boolean 值是否已在 Java 中更改

转载 作者:行者123 更新时间:2023-11-29 06:40:39 25 4
gpt4 key购买 nike

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

简化版代码如下:

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?

}
}});

}

最佳答案

[is] there was a built in method or functionality where I could detect if a booleans value had changed in the 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
}
}

setTest1setTest2 调用替换这些变量的所有赋值,以可靠地检测 test1test2.

关于java - 检查 boolean 值是否已在 Java 中更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12719390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com