如何在 Java GUI 中设置按钮的背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4172940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:19:19  来源:igfitidea点击:

How to set background color of a button in Java GUI?

javaswingjbutton

提问by Salar

Below is the code which creates 9 buttons in gridlayout form on a specific pannel3. What i want is to make the background of each button black with grey text over it. Can anyone help please?

下面是在特定pannel3上以gridlayout形式创建9个按钮的代码。我想要的是将每个按钮的背景设为黑色,上面有灰色文本。有人可以帮忙吗?

 for(int i=1;i<=9;i++)
 {
     p3.add(new JButton(""+i));
 }

采纳答案by Pablo Santa Cruz

Check out JButtondocumentation. Take special attention to setBackgroundand setForegroundmethods inherited from JComponent.

查看JButton文档。要特别重视setBackgroundsetForeground方法的继承JComponent

Something like:

就像是:

for(int i=1;i<=9;i++)
{
    JButton btn = new JButton(String.valueOf(i));
    btn.setBackground(Color.BLACK);
    btn.setForeground(Color.GRAY);
    p3.add(btn);
}

回答by dacwe

for(int i=1;i<=9;i++) {
    p3.add(new JButton(""+i) {{
        // initialize the JButton directly
        setBackground(Color.BLACK);
        setForeground(Color.GRAY);
    }});
}

回答by npinti

Use the setBackgroundmethod to set the background and setForegroundto change the colour of your text. Note however, that putting grey text over a black background might make your text a bit tough to read.

使用setBackground方法设置背景并使用setForeground更改文本的颜色。但是请注意,将灰色文本放在黑色背景上可能会使您的文本难以阅读。

回答by Tanner

You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.

您可能必须也可能不必使用 setOpaque 方法来确保通过将 true 传递给该方法来显示颜色。

回答by GregNash

It seems that the setBackground() method doesn't work well on some platforms (I'm using Windows 7). I found this answerto this questionhelpful. However, I didn't entirely use it to solve my problem. Instead, I decided it'd be much easier and almost as aesthetic to color a panel next to the button.

似乎 setBackground() 方法在某些平台上不能很好地工作(我使用的是 Windows 7)。我发现这个答案这个问题有帮助。但是,我并没有完全使用它来解决我的问题。相反,我决定为按钮旁边的面板着色会更容易,而且几乎同样美观。

回答by Ali Mohammadi

Simple:

简单的:

btn.setBackground(Color.red);

btn.setBackground(Color.red);

To use RGB values:

要使用 RGB 值:

btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));

btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));

回答by luca

Changing the background property might not be enough as the component won't look like a button anymore. You might need to re-implement the paint method as in hereto get a better result:

更改背景属性可能还不够,因为组件将不再像按钮。您可能需要重新实现这里的paint方法以获得更好的结果:

enter image description here

在此处输入图片说明