简体   繁体   English

如何更改背景颜色?

[英]How do I make the background color change?

I am working on a program that has 5 different color radio buttons, and when clicked, the background should change to the corresponding color. 我正在使用一个具有5个不同颜色的单选按钮的程序,单击该按钮后,背景应更改为相应的颜色。 My background is not changing. 我的背景没有改变。 I cannot for the life of me figure out what is wrong with my code. 我一辈子都无法弄清楚我的代码出了什么问题。 Can someone out there help me find my problem? 有人可以帮我找到我的问题吗? Thank you! 谢谢! My code is as follows: 我的代码如下:

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)
{
}

More than likely you're using java.awt.CheckBox components (from your earlier question ) which respond to ItemListeners but not ActionListeners . 您很有可能使用java.awt.CheckBox组件(来自您先前的问题 ),这些组件响应ItemListeners而不是ActionListeners Therefore move your code to the itemStateChanged method 因此,将您的代码移至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);
    }
}
  • Use braces to delimit scope 使用花括号界定范围
  • Notice the use of newer uppercase Color constants 注意使用更新的大写Color常量
  • AWT is an old limited UI library compared to the newer lightweight Swing which is feature rich. 与功能丰富的新版轻量级Swing相比,AWT是一个有限的旧UI库。 Swing JCheckBoxes support ActionListeners Swing JCheckBoxes支持ActionListeners

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM