更改JButton的背景颜色始终显示为灰色

时间:2015-12-18 18:44:56

标签: java swing background jbutton

我正在创建一个GUI界面,我正在尝试使用以下代码更改窗口的背景和前景色:

  import java.awt.Color;
  import java.awt.Component;
  import java.awt.Container;

  import javax.swing.JButton;
  import javax.swing.JFrame;
  import javax.swing.JPanel;

  public class Test
  {

public static void changeColor(String typeOfColor, Component component, Color color)
{
    if (typeOfColor.equals("Background"))
    {
        component.setBackground(color);
    }
    else if (typeOfColor.equals("Foreground"))
    {
        component.setForeground(color);
    }

    if (component instanceof Container)
    {
        for (Component child : ((Container) component).getComponents())
        {
            changeColor(typeOfColor, child, color);
        }
    }
}

public static void main(String[] args)
{
    JPanel panel = new JPanel();
    JButton cancelButton = new JButton("Cancel");
    panel.add(cancelButton);

    changeColor("Background", panel, new Color(0, 255, 0));

    JFrame frame = new JFrame("Frame");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(panel);
    frame.setVisible(true);
    frame.pack();
}
}

但是,无论我选择什么颜色,按钮仍然会将背景颜色显示为灰色。如何正确更改背景颜色?我环顾四周,大多数答案都提到了setBackground方法,但这对我不起作用。

提前致谢!

3 个答案:

答案 0 :(得分:3)

检查当前程序这些行的顺序:

panel.add(cancelButton);
changeColor("Background", panel, new Color(0, 255, 0));

如果您按此顺序拥有它们,则会获得此输出:

enter image description here

但是如果你改变顺序:

changeColor("Background", panel, new Color(0, 255, 0));
panel.add(cancelButton);

你明白了:

enter image description here

答案 1 :(得分:1)

Nicholas Smith解决了我的问题。

在评论中,他提到“可能是您的特定LookAndFeel中的JButton的背景颜色无法覆盖。”

我在我的代码中设置了外观,一旦我删除了那部分代码,我的按钮的背景颜色就被成功更改了。

谢谢你!

答案 2 :(得分:0)

您应该使用LookAndFeel更改GUI的UIManager.setLookAndFeel()

在MacOSX中发生了好几次

相关问题