如何设置JButton的按钮颜色(非背景颜色)

6
我有一个JButton,我想把它的背景颜色改成白色。当使用Metal外观时,使用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的按钮颜色为白色。我该怎么做?

尝试覆盖JButtonpaintComponent(Graphics g)方法,并在那里进行自定义绘制。 - mre
我想使用Windows LAF。我在想你的OSX和Linux用户想看到什么?我敢打赌不会是Windows LAF(即使这是可行的)。;) - Andrew Thompson
@Andrew Thompson:别担心,我正在使用系统的LAF,但现在要求仅限于Windows系统。 :) - Joseph Trebbien
我的第一个问题是“为什么?”这个按钮有什么特别之处,需要与其他按钮颜色和外观不同? - John Gardner
5个回答

4

您需要决定是否值得花费精力,但是您可以根据此示例(由@mKorbel提供)创建自己的ButtonUI


我认为我将不得不这样做。谢谢你提供的链接。 - Joseph Trebbien

4

我在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);
    }
}

当您按原样运行代码时,它似乎可以正常工作。也就是说,当您单击按钮时,您会看到边框更改。但是,如果您使用Windows XP LAF运行,则边框永远不会更改,因此您无法看到按钮单击效果。
因此,我猜测问题出在WindowUI上,您需要自定义UI,这可能太复杂了,所以我没有解决方案。

1
作为参考,在Mac OS X中,当选择“Test 1”时,“BackgroundButton”的外观如下所示:链接 - trashgod
@camickr @trashgod 这与macOS无关,super.paintComponent(g);这行应该放在setColorfillRect函数之前,否则它看起来就像你所说的那样没有填充。 - Celuk

2
但我仍然认为Darryl修改后的答案是正确的,因为可以跨平台使用UIManager.get("Button.gradient")
编辑:正确的答案应该是- Nimbus或一些自定义L&F,为什么要重新发明轮子(由Rob提供)。

1

您最好的选择是使用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));

-1

与其搞乱按钮的背景颜色,你能用其他方式来显示你想要表达的意思吗?

比如展示一个图标,让按钮变粗而不是使用普通文本等。

仅通过改变背景颜色来表示某些东西并不总是明显的,而且根据用户系统的颜色设置,可能会很刺眼或者看不见。

例如,如果用户在“高对比度”模式下运行Windows呢?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接