Java 如何更改背景颜色?
我正在开发一个有5个不同颜色单选按钮的程序,当单击时,背景应更改为相应的颜色。我的背景没有改变。 我一辈子都搞不清楚我的代码出了什么问题。外面有人能帮我找到我的问题吗?非常感谢。 我的代码如下:Java 如何更改背景颜色?,java,swing,background,awt,listener,Java,Swing,Background,Awt,Listener,我正在开发一个有5个不同颜色单选按钮的程序,当单击时,背景应更改为相应的颜色。我的背景没有改变。 我一辈子都搞不清楚我的代码出了什么问题。外面有人能帮我找到我的问题吗?非常感谢。 我的代码如下: public void actionPerformed(ActionEvent e) { if (blue.getState()) f.setBackground(Color.blue); else if (red.getState()) f.setBackground(Color.re
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
- 与功能丰富的较新的轻量级UI库相比,AWT是一个旧的有限UI库。Swing
支持JCheckbox
ActionListeners
java.awt.CheckBox
组件(来自),这些组件响应项目监听器
,但不响应操作监听器
。因此,将代码移动到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
- 与功能丰富的较新的轻量级UI库相比,AWT是一个旧的有限UI库。Swing
支持JCheckbox
ActionListeners
JRadioButton
或RadioButton
?您是否使用JRadioButton
或RadioButton
?