如何在Java GUI中设置按钮的背景颜色?
下面的代码在特定的 pannel3 上以网格布局形式创建 9 个按钮。我想要的是将每个按钮的背景设为黑色,并在其上显示灰色文本。 有人可以帮忙吗?
for(int i=1;i<=9;i++)
{
p3.add(new JButton(""+i));
}
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?
for(int i=1;i<=9;i++)
{
p3.add(new JButton(""+i));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
查看 JButton 文档。请特别注意从
JComponent
继承的setBackground
和setForeground
方法。像这样的东西:
Check out JButton documentation. Take special attention to
setBackground
andsetForeground
methods inherited fromJComponent
.Something like:
简单:
btn.setBackground(Color.red);
要使用 RGB 值:
btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));< /代码>
Simple:
btn.setBackground(Color.red);
To use RGB values:
btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));
更改背景属性可能还不够,因为组件看起来不再像按钮。您可能需要按照此处重新实现paint方法以获得更好的结果:
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 here to get a better result:
您可能需要也可能不需要使用 setOpaque 方法来通过将 true 传递给该方法来确保颜色显示。
You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.
看来 setBackground() 方法在某些平台上效果不佳(我使用的是 Windows 7)。我找到了这个答案到这个问题有帮助。但是,我并没有完全用它来解决我的问题。相反,我认为给按钮旁边的面板上色会更容易,而且几乎同样美观。
It seems that the setBackground() method doesn't work well on some platforms (I'm using 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.
使用 setBackground 方法设置背景和 setForeground 更改文本的颜色。但请注意,将灰色文本放在黑色背景上可能会使文本有点难以阅读。
Use the setBackground method to set the background and setForeground to 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.
我尝试了以前的解决方案,但仍然无法改变颜色。看到另一篇文章并解决了我的问题。该按钮由不同的层组成。删除所有这些有助于:
I tried the previous solutions but still couldn't change the color. Came across another article and solved my problem. The button is made of different layers. Removing all of them helps: