Setting background color for JButton

I have a question about setting the background color to JButton.

It seems that this method only changes the border color. Here is the difference (left JButton):

enter image description here

Is there any way to make the background the same?

I use setLookAndFeelon Windows 8.

+1
source share
2 answers

This will work with both metal (default) and 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);
    }
}
+17
source

Use the .setOpaque (true) button on the button.

0
source

Source: https://habr.com/ru/post/1616831/


All Articles