繁体   English   中英

如何更改背景颜色?

[英]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常量
  • 与功能丰富的新版轻量级Swing相比,AWT是一个有限的旧UI库。 Swing JCheckBoxes支持ActionListeners

暂无
暂无

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

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