[英]Trying to change the color of a J Button back and forth when it is clicked
I am still a newbie when it comes to Java and I am attempting to change the color of a button every time it is clicked by using action listeners.我仍然是 Java 的新手,我试图通过使用动作侦听器在每次单击按钮时更改按钮的颜色。 But I have tried many different ways and have come to a road block... I have tried using a Boolean but I am still having problems with figuring this out.
但是我尝试了许多不同的方法并遇到了障碍......我尝试过使用布尔值,但我仍然无法解决这个问题。
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;
}
}
});
In this context...在这种情况下...
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
will always be false
, as it's declared locally within the actionPerformed
method. right
将始终为false
,因为它是在actionPerformed
方法中本地声明的。
Instead, make a instance field of the ActionListener
, for example...相反,创建
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;
}
}
});
Also, change
never changes, so it's always BLACK
, in which case I might be tempted to do something more like this...此外,
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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.