简体   繁体   English

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

[英]Changing the background color of JButton always shows as grey

I am making a GUI interface and I am trying to change the background and foreground color of my windows with the following code: 我正在制作一个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();
}
}

However, no matter what is the color I choose, the buttons still display the background color as grey. 但是,无论我选择什么颜色,按钮仍然将背景颜色显示为灰色。 How do I change the background color properly? 如何正确更改背景颜色? I have looked around and most answers mention the setBackground method, but that does not work for me. 我环顾四周,大多数答案都提到了setBackground方法,但这对我不起作用。

Thanks in advance! 提前致谢!

Check on your current program the order of these lines: 检查当前程序中这些行的顺序:

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

If you have them in this order you get this output: 如果按此顺序排列它们,则会得到以下输出:

在此处输入图片说明

But if you change the order: 但是,如果您更改顺序:

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

You get this: 你得到这个:

在此处输入图片说明

Nicholas Smith solved my issue. 尼古拉斯·史密斯解决了我的问题。

In the comments, he mentioned "It could be the background color for a JButton in your specific LookAndFeel can't be overridden." 在评论中,他提到“它可能是您特定LookAndFeel中JButton的背景颜色,不能覆盖。”

I was setting the look and feel in my code and once I removed that part of the code, my buttons' background color was changed successfully. 我在代码中设置外观,一旦删除了代码的那部分,按钮的背景色就成功更改了。

Thanks to you! 谢谢你!

You should change the LookAndFeel of your GUI with UIManager.setLookAndFeel() . 您应该使用UIManager.setLookAndFeel()更改GUI的LookAndFeel

It happened to me several times in MacOSX 在MacOSX中,它发生了几次

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

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