[英]How to set background color of a button in Java GUI?
Below is the code which creates 9 buttons in gridlayout form on a specific pannel3. 下面是在特定pannel3上以gridlayout形式创建9个按钮的代码。 What i want is to make the background of each button black with grey text over it.
我想要的是使每个按钮的背景为黑色,上面有灰色文字。 Can anyone help please?
有人可以帮忙吗?
for(int i=1;i<=9;i++)
{
p3.add(new JButton(""+i));
}
Check out JButton documentation. 查看JButton文档。 Take special attention to
setBackground
and setForeground
methods inherited from JComponent
. 请特别注意从
JComponent
继承的setBackground
和setForeground
方法。
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);
}
Simple: 简单:
btn.setBackground(Color.red);
To use RGB values: 要使用RGB值:
btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));
for(int i=1;i<=9;i++) {
p3.add(new JButton(""+i) {{
// initialize the JButton directly
setBackground(Color.BLACK);
setForeground(Color.GRAY);
}});
}
您可能需要也可能不必使用setOpaque方法来确保通过将true传递给方法来显示颜色。
Use the setBackground method to set the background and setForeground to change the colour of your text. 使用setBackground方法设置background和setForeground以更改文本的颜色。 Note however, that putting grey text over a black background might make your text a bit tough to read.
但请注意,将灰色文本放在黑色背景上可能会使您的文本难以阅读。
It seems that the setBackground() method doesn't work well on some platforms (I'm using Windows 7). 似乎setBackground()方法在某些平台上运行不正常(我使用的是Windows 7)。 I found this answer to this question helpful.
我发现这个答案对这个问题有帮助。 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.
相反,我认为为按钮旁边的面板着色会更容易,也更美观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.