tags:

views:

413

answers:

2

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);
+10  A: 

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.

Peter Lang
+6  A: 

The JLabel background is transparent by default. Set the opacity at true like that:

label.setOpaque(true);
Yannick L.