为什么 setBackground 到 JButton 不起作用?
我有以下简单的代码:
btn = new JButton();
btn.setBackground(backgroundColor)
我在使用时工作:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
但在我评论上面的行后它停止工作。有谁知道为什么会发生这种情况以及如何在不使用明确的外观和感觉的情况下为按钮设置背景颜色?
添加
在我看来,我需要使用getBackground
。但我不知道怎么办。
I have the following simple code:
btn = new JButton();
btn.setBackground(backgroundColor)
I worked when I used:
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
But it stopped to work after I have commented the above line. Does anybody know why it can happen and how I can set a background color to a button without the usage of an explicit Look and Feel?
ADDED
It seems to me that I need to use getBackground
. But I do not know how.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
需要将元素的 Opaque 设置为 true 才能填充颜色
it is necessary to set Opaque of the element to true for color to be filled
添加 btn.setBorderPainted(false)
add btn.setBorderPainted(false)
来自 setBackground() javadoc:
也许你的 LAF 只是忽略了它。
From setBackground() javadoc:
Maybe your LAF just ignored it.
问题也可能与您创建按钮的方式有关。检查上面的代码是否:
}
Problem also can be with the way you are creating the button. Check if the code above:
}
只需单击要为其设置背景的按钮一次,然后转到属性窗口。在那里,第二个选项将是背景。单击其省略号,您可以根据自己的喜好更改颜色。在运行程序之前,颜色不会显示在框架中的按钮上。您可以看到按钮的颜色是您喜欢的。
Simply click once on the button you want to set background for, and then go to the properties window. Over there, the second option will be background. Click on its ellipsis, and you can change the color to your liking. The color won't be displayed on the button in your frame until after you run the program. You can see that the button is in the color you preferred.