gpt4 book ai didi

java - 更改不同类的变量

转载 作者:行者123 更新时间:2023-12-01 06:52:10 25 4
gpt4 key购买 nike

我试图让一个按钮调用另一个类中的方法来更新某些内容的颜色,但是它没有按我预期的方式运行。问题是颜色改变了一次但再也没有改变过。

这是发生更改的文件:

public class Status
{
//initial conditions
Color pedLightColor = Color.RED;
Color warnLightsColor = Color.GREEN;
Boolean GatesUp= true;
Color drawbridgeColor = Color.green;
public Status()
{
}

public Color getPedestrianStatus()
{
return pedLightColor;
}

public void setPedestrianColor(Color c)
{
if(c.equals(Color.RED))
{
pedLightColor=Color.green;
System.out.println("Pedestrian Light color changed to " + pedLightColor);
}
else
{
pedLightColor=Color.red;
System.out.println("Pedestrian Light color changed to " + pedLightColor);
}
}
}

其调用方式如下:

pedButton.addActionListener(new ActionListener() 
{
@Override
public void actionPerformed(ActionEvent event)
{
System.out.println("Control Unit/Pedestrian Button Clicked");
Status status = new Status();
status.setPedestrianColor(status.getPedestrianStatus());
System.out.println(status.getPedestrianStatus());
}
});

目前我相信我正在通过以当前颜色作为参数调用 setPedestrianColor() 方法来更改颜色。然而,我不确定为什么一旦你第二次按下按钮,颜色应该是绿色,所以它应该变回红色,但事实并非如此。任何对我出错的地方的建议都会受到赞赏。

最佳答案

您的 Status 对象需要是全局的或以不同的方式实例化。每次调用 actionPerformed 后,颜色都会发生变化,然后对象就会被丢弃。所以它永远不会真正从红色变为绿色。

关于java - 更改不同类的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22538633/

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