Java 将背景颜色设置为 JButton
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18165160/
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
Setting background color to JButton
提问by ro-E
I have a question about setting the background color to JButton
.
我有一个关于将背景颜色设置为 的问题JButton
。
It seems that the this method only changes the color of the border. Here is the difference (left is jButton
):
看来这个方法只改变了边框的颜色。这是区别(左边是jButton
):
Is there a way to make the background the same?
有没有办法使背景相同?
I'm using setLookAndFeel
on Windows 8.
我setLookAndFeel
在 Windows 8 上使用。
采纳答案by Andrew Thompson
This will work with either the Metal (default) or Windows PLAFs.
这将适用于 Metal(默认)或 Windows PLAF。
import java.awt.Color;
import javax.swing.*;
class ColoredButton {
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JButton b1 = new JButton("Button 1");
b1.setBackground(Color.RED);
// these next two lines do the magic..
b1.setContentAreaFilled(false);
b1.setOpaque(true);
JOptionPane.showMessageDialog(null, b1);
};
SwingUtilities.invokeLater(r);
}
}
回答by Xabster
Use .setOpaque(true) on the button.
在按钮上使用 .setOpaque(true) 。