Setting background color to JButton [duplicate]

为君一笑 提交于 2019-12-01 13:08:04

This will work with either the Metal (default) or Windows PLAFs.

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

Use .setOpaque(true) on the button.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!