关于Java:如何设置JButton的按钮颜色(不是背景颜色)

How to set the button color of a JButton (not background color)

我有一个JButton,我想将其背景颜色更改为白色。 使用"金属外观"时,我使用setBackground达到了预期的效果:

Metal look-and-feel-styled JButton with a white background

不幸的是,使用Windows LAF时,"背景色"的概念有所不同。 背景颜色是按钮周围绘制的颜色:

Windows look-and-feel-styled JButton with a white background

我想使用Windows LAF,但允许将此JButton的按钮颜色更改为白色。 我该怎么做呢?


您必须决定是否值得付出努力,但始终可以创建自己的ButtonUI,如@mKorbel所示,如本示例所示。


我在XP上使用JDK 6。看起来Window UI并没有以比1多的方式遵循正常的绘制规则。您注意到setBackground()不起作用。您应该能够通过告诉组件不要填写内容区域来进行自定义绘制:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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允许您使用MattePainter使用.setBackgroundPainter(Painter)为背景设置Painter,从而实现所需的效果。有了JXButton从JButton扩展而来的更改,您的代码中的更改就很小

1
2
3
4
Color bg = new Color(new Random().nextInt(16777215)); // Random color

JButton button = new JButton();
button.setBackground(bg);

会成为

1
2
JXButton button = new JXButton();
button.setBackgroundPainter(new MattePainter(bg));

但我仍然认为(由Darryl修改)是正确的UIManager.get(" Button.gradient"),因为它将是跨平台的

编辑:正确的答案将是-Nimbus或一些Custom L&F,为什么要重新发明轮子(由Rob)


除了可以弄乱按钮的背景颜色之外,您还可以做其他尝试以其他方式显示的指示吗?

显示图标,使按钮变为粗体,而不是纯文本等。

仅通过不同的背景颜色指示某事并不总是显而易见的,并且取决于用户的系统颜色,可能会感到震颤或不可见。

例如,如果用户以"高对比度"模式运行Windows,该怎么办?