gpt4 book ai didi

java - 尝试在单击 J 按钮时来回更改其颜色

转载 作者:行者123 更新时间:2023-12-01 20:02:44 25 4
gpt4 key购买 nike

对于 Java 来说,我还是个新手,我尝试使用操作监听器在每次单击按钮时更改按钮的颜色。但我尝试了很多不同的方法,但遇到了障碍...我尝试使用 boolean 值,但在解决这个问题时仍然遇到问题。

Color change = Color.BLACK    
B.setForeground(change);
B.setContentAreaFilled(false);
B.setFocusPainted(false);
B.setBounds(100, 175, 75, 75);

R.add(B); // R is the JFrame the button is added to...

B.addActionListener(new ActionListener() { //Action Listener when pressing should change the color from Black to Red
public void actionPerformed(ActionEvent e) {
boolean right = false;
if (change == Color.BLACK) {
right = true;
B.setForeground(Color.red);
}
if (right == true) {
B.setForeground(Color.BLACK);
right = false;
}

}

});

最佳答案

在这种情况下...

B.addActionListener(new ActionListener() { //Action Listener when pressing should change the color from Black to Red
public void actionPerformed(ActionEvent e) {
boolean right = false;
if (change == Color.BLACK) {
right = true;
B.setForeground(Color.red);
}
if (right == true) {
B.setForeground(Color.BLACK);
right = false;
}
}
});

right 始终为 false,因为它是在 actionPerformed 方法中本地声明的。

相反,创建一个 ActionListener 的实例字段,例如...

B.addActionListener(new ActionListener() { //Action Listener when pressing should change the color from Black to Red
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (change == Color.BLACK) {
right = true;
B.setForeground(Color.red);
}
if (right == true) {
B.setForeground(Color.BLACK);
right = false;
}

}

});

另外,change永远不会改变,所以它总是BLACK,在这种情况下,我可能会想做更多类似这样的事情......

B.addActionListener(new ActionListener() { //Action Listener when pressing should change the color from Black to Red
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
B.setForeground(Color.red);
} else if (right) {
B.setForeground(Color.BLACK);
}
right = !right;
}

});

关于java - 尝试在单击 J 按钮时来回更改其颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004050/

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