在Windows上设置JButton的背景颜色

5

我有一个JButton,想把它的背景设置成一个颜色。

JButton button = new JButton();
button.setVisible(true);
button.setPreferredSize(new Dimension(student_scroll.getWidth(), 50));
button.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1));
button.setBackground(Color.BLACK);
button.setForeground(Color.WHITE);
button.setOpaque(true);

我在Mac上使用这个,显示效果很好。但是,在Windows上尝试时,前景色为白色(应该是这样的),但背景为空白。

设置JButton的背景颜色

建议添加button.setContentAreaFilled(false);,我已经添加了,但没有效果。大多数人建议添加button.setOpaque(true);,我也已经添加了。

还需要做什么才能使其显示黑色背景?

编辑

如要求所述,以下是SSCCE:

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MainSwing extends JFrame {
    private static final long serialVersionUID = -8231889836024827530L;

    public static void main(String[] args) {
        try {
            System.setProperty("apple.laf.useScreenMenuBar", "true");
            System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Test");
            UIManager.put("ScrollBarUI", "main.CustomScrollBarUI");
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch(ClassNotFoundException e) {
            System.out.println("ClassNotFoundException: " + e.getMessage());
    }
    catch(InstantiationException e) {
            System.out.println("InstantiationException: " + e.getMessage());
    }
    catch(IllegalAccessException e) {
            System.out.println("IllegalAccessException: " + e.getMessage());
    }
    catch(UnsupportedLookAndFeelException e) {
            System.out.println("UnsupportedLookAndFeelException: " + e.getMessage());
    }
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                JFrame frame = new JFrame() {

                    Container c = getContentPane();
                    JButton button = new JButton("Hello");
                    {
                        button.setText("Hello");
                        button.setVisible(true);
                        button.setPreferredSize(new Dimension(100, 50));
                        button.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1));
                        button.setBackground(Color.BLACK);
                        button.setForeground(Color.WHITE);
                        button.setOpaque(true);
                        c.add(button);
                    }

                };
                frame.setSize(500, 500);
                frame.setBackground(Color.BLACK);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

似乎问题与这行代码有关:UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());,因为当我将其移除时,按钮就变成了黑色。


对我来说运行良好。请发布一个合适的SSCCE,以演示问题。所以你只需要一个带有按钮的框架来进行测试。整个程序只需10-15行代码。 - camickr
1
setContentAreaFilled(false)setBorderPainted(false)。"填充"效果由外观委托提供,我不知道任何方法可以影响它使用的颜色。 - MadProgrammer
不需要 button.setVisible(true);。只需将其添加到顶级窗口(框架、窗口、对话框等)中的容器中,该容器在添加组件后进行打包,然后设置可见性。如果按钮没有文本,则可以使用(可能是透明的)图像轻松设置大小。如果按钮有文本,则最好从字体大小和文本内容以及包含它的按钮的边距和边框来确定大小。在任何情况下,我们都不需要设置首选大小。 - Andrew Thompson
@Moon Cheesez 例如 - mKorbel
2个回答

5
我猜测从那些UIManager的键值对中得知PLAF是基于OS X的Aqua PLAF。这似乎是问题的一部分。这里是在Windows上没有填充内容区域的样子。

enter image description here

import java.awt.*;
import javax.swing.*;

public class MainSwing extends JFrame {

    public static void main(String[] args) {
        try {
            System.setProperty("apple.laf.useScreenMenuBar", "true");
            System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Test");
            UIManager.put("ScrollBarUI", "main.CustomScrollBarUI");
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace(); // more info for less LOC!
        }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame() {

                    Container c = getContentPane();
                    JButton button = new JButton("Hello");

                    {
                        c.setLayout(new GridLayout(0,1));
                        c.add(new JButton("Hi"));
                        button.setText(UIManager.getSystemLookAndFeelClassName());
                        button.setVisible(true);
                        button.setPreferredSize(new Dimension(400, 100));
                        button.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1));
                        button.setContentAreaFilled(false);
                        button.setBackground(Color.BLACK);
                        button.setForeground(Color.WHITE);
                        button.setOpaque(true);
                        c.add(button);
                    }
                };
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

4
哇,这对我在Windows上也适用。我发现 setOpaque(true) 语句很重要,并且必须在 setContentAreaFilled(false) 语句之后调用,因为该语句显然会调用 setOpaque(false),而我并不知道这一点。每天都会学到新东西。我想我应该先阅读您在“设置按钮背景颜色”中的答案 :) - camickr
@camickr 总是明智的分析。 :) 我也看到了你在答案中建议的绕过整个 PLAF“问题”的价值。 - Andrew Thompson
回到未来,这也解决了Jython JButtons的同样问题。 - Moon Cheesez

3
似乎问题与这行代码有关:UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());因为当我删除它时,按钮是黑色的。这提供了我们在创建SSCCE之前所没有的额外信息(这就是为什么您应该在问题中始终发布SSCCE的原因)。这也告诉您问题不在于您的代码,而在于LAF。Windows LAF忽略setBackground(...)方法并绘制自己的背景。其中一个选项是向所需颜色的按钮添加图标。然后,您可以配置文本在按钮中心绘制:
import java.awt.*;
import javax.swing.*;

public class ColorIcon implements Icon
{
    private Color color;
    private int width;
    private int height;

    public ColorIcon(Color color, int width, int height)
    {
        this.color = color;
        this.width = width;
        this.height = height;
    }

    public int getIconWidth()
    {
        return width;
    }

    public int getIconHeight()
    {
        return height;
    }

    public void paintIcon(Component c, Graphics g, int x, int y)
    {
        g.setColor(color);
        g.fillRect(x, y, width, height);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public static void createAndShowGUI()
    {
        JPanel panel = new JPanel( new GridLayout(2, 2) );

        for (int i = 0; i < 4; i++)
        {
            Icon icon = new ColorIcon(Color.RED, 50, 50);
            JButton label = new JButton( icon );
            label.setText("" + i);
            label.setHorizontalTextPosition(JButton.CENTER);
            label.setVerticalTextPosition(JButton.CENTER);
            panel.add(label);
        }

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel);
        f.setSize(200, 200);
        f.setLocationRelativeTo( null );
        f.setVisible(true);
    }
}

然后它应该适用于所有的LAF。

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