我有一个JButton,我想把它的背景颜色改成白色。当使用Metal外观时,使用setBackground可以实现所需效果:
不幸的是,当使用Windows LAF时,“背景颜色”的概念是不同的;背景颜色是绘制在按钮周围的颜色:
我想使用Windows LAF,但允许更改此JButton的按钮颜色为白色。我该怎么做?
![Metal look-and-feel-styled JButton with a white background](https://istack.dev59.com/s4RFI.webp)
![Windows look-and-feel-styled JButton with a white background](https://istack.dev59.com/w6Vwe.webp)
您需要决定是否值得花费精力,但是您可以根据此示例(由@mKorbel提供)创建自己的ButtonUI
。
我在XP上使用JDK 6。看起来Window UI不遵循正常的绘制规则,有多个方面都是如此。就像你注意到的那样,setBackground()不起作用。您可以通过告诉组件不要填充内容区域来进行自定义绘制:
import java.awt.*;
import javax.swing.*;
public class ButtonBackground extends JFrame
{
public ButtonBackground()
{
setLayout( new FlowLayout() );
JButton normal = new JButton("Normal");
add(normal);
JButton test1 = new JButton("Test 1")
{
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor( Color.GREEN );
g.fillRect(0, 0, getSize().width, getSize().height);
}
};
test1.setContentAreaFilled(false);
add(test1);
}
public static void main(String[] args)
{
try
{
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e2) {}
ButtonBackground frame = new ButtonBackground();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
super.paintComponent(g);
这行应该放在setColor
和fillRect
函数之前,否则它看起来就像你所说的那样没有填充。 - Celuk您最好的选择是使用SwingX:
JXButton允许您使用.setBackgroundPainter(Painter)
设置背景绘制器,使用MattePainter可以实现您想要的效果。由于JXButton继承自JButton,在您的代码中更改最小:
Color bg = new Color(new Random().nextInt(16777215)); // Random color
JButton button = new JButton();
button.setBackground(bg);
会变成
JXButton button = new JXButton();
button.setBackgroundPainter(new MattePainter(bg));
与其搞乱按钮的背景颜色,你能用其他方式来显示你想要表达的意思吗?
比如展示一个图标,让按钮变粗而不是使用普通文本等。
仅通过改变背景颜色来表示某些东西并不总是明显的,而且根据用户系统的颜色设置,可能会很刺眼或者看不见。
例如,如果用户在“高对比度”模式下运行Windows呢?
JButton
的paintComponent(Graphics g)
方法,并在那里进行自定义绘制。 - mre