1

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

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

enter image description here

Is there a way to make the background the same?

I'm using setLookAndFeel on Windows 8.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ro-E
  • 279
  • 1
  • 5
  • 16

2 Answers2

20

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

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

class ColoredButton {

    public static void main(String[] args) {
        Runnable r = () -> {
            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);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

Use .setOpaque(true) on the button.

Xabster
  • 3,710
  • 15
  • 21