[英]How do I make the background color change?
我正在使用一个具有5个不同颜色的单选按钮的程序,单击该按钮后,背景应更改为相应的颜色。 我的背景没有改变。 我一辈子都无法弄清楚我的代码出了什么问题。 有人可以帮我找到我的问题吗? 谢谢! 我的代码如下:
public void actionPerformed(ActionEvent e)
{
if (blue.getState()) f.setBackground(Color.blue);
else if (red.getState()) f.setBackground(Color.red);
else if (yellow.getState()) f.setBackground(Color.yellow);
else if (pink.getState()) f.setBackground(Color.pink);
else if (gray.getState()) f.setBackground(Color.gray);
} //end of actionPerformed method
public void itemStateChanged(ItemEvent e)
{
}
您很有可能使用java.awt.CheckBox
组件(来自您先前的问题 ),这些组件响应ItemListeners
而不是ActionListeners
。 因此,将您的代码移至itemStateChanged
方法
public void itemStateChanged(ItemEvent e) {
if (blue.getState()) {
f.setBackground(Color.BLUE);
} else if (red.getState()) {
f.setBackground(Color.RED);
} else if (yellow.getState()) {
f.setBackground(Color.YELLOE);
} else if (pink.getState()) {
f.setBackground(Color.PINK);
} else if (gray.getState()) {
f.setBackground(Color.GRAY);
}
}
Color
常量 JCheckBoxes
支持ActionListeners
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.