[英]How to set the button color of a JButton (not background color)
我有一个JButton
,我想将其背景颜色更改为白色。 使用 Metal Look And Feel 时,我使用setBackground
达到了预期的效果:
不幸的是,使用 Windows LAF 时,“背景颜色”的概念有所不同; 背景颜色是按钮周围绘制的颜色:
我想使用 Windows LAF,但允许将此JButton
的按钮颜色更改为白色。 我该怎么做呢?
您必须决定是否值得付出努力,但您始终可以创建自己的ButtonUI
,如本示例所示,感谢@mKorbel。
我在 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)
{
g.setColor( Color.GREEN );
g.fillRect(0, 0, getSize().width, getSize().height);
super.paintComponent(g);
}
};
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);
}
}
当您按原样运行代码时,它似乎可以正常工作。 那就是当您单击按钮时,您会看到边框发生变化。 但是,如果您使用 Windows XP LAF 运行,边框永远不会改变,您看不到按钮单击效果。
因此,我想问题出在 WindowUI 上,您需要自定义 UI,这可能太复杂了,所以我没有解决方案。
您最好的选择是使用 SwingX:
JXButton 允许您使用.setBackgroundPainter(Painter)
为背景设置 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));
但我仍然认为(由 Darryl 修改)是正确的UIManager.get("Button.gradient") ,因为它是跨平台的
编辑:正确答案是 - Nimbus 或一些Custom L&F ,为什么要重新发明轮子(Rob)
而不是弄乱按钮的背景颜色,你能做任何你试图以不同方式显示的指示吗?
显示图标,使按钮变为粗体而不是纯文本等。
仅通过不同的背景颜色来表示某些东西并不总是很明显,并且根据用户的系统 colors,可能会不和谐或不可见。
例如,如果用户在“高对比度”模式下运行 windows 怎么办?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.