将背景颜色设置为JButton

时间:2013-08-10 18:36:34

标签: java swing colors jbutton

我有一个关于将背景颜色设置为JButton的问题。

似乎此方法仅更改边框的颜色。这是区别(左边是jButton):

enter image description here

有没有办法让背景变得相同?

我在Windows 8上使用setLookAndFeel

2 个答案:

答案 0 :(得分:15)

这适用于Metal(默认)或Windows PLAF。

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

class ColoredButton {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                JButton b1 = new JButton("Button 1");
                b1.setBackground(Color.RED);
                // these next two lines do the magic..
                b1.setContentAreaFilled(false);
                b1.setOpaque(true);

                JOptionPane.showMessageDialog(null, b1);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

答案 1 :(得分:0)

在按钮上使用.setOpaque(true)。

相关问题