How do I set a JLabel's background color?

java, jlabel, swing

Solution

Use

label.setOpaque(true);

Otherwise the background is not painted, since the default of `opaque` is `false` for `JLabel`.

From the JavaDocs:

If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.

For more information, read the Java Tutorial How to Use Labels.

Problem

In my `JPanel`, I set the background of a `JLabel` to a different color. I can see the word "Test" and it's blue, but the background doesn't change at all. How can I get it to show? ``` this.setBackground(Color.white); JLabel label = new JLabel("Test"); label.setForeground(Color.blue); label.setBackground(Color.lightGray); this.add(label); ```

Original source