How do I set a JLabel's background color? How do I set a JLabel's background color? java java

How do I set a JLabel's background color?


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.


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

label.setOpaque(true);


You must set the setOpaque(true) to true other wise the background will not be painted to the form. I think from reading that if it is not set to true that it will paint some or not any of its pixels to the form. The background is transparent by default which seems odd to me at least but in the way of programming you have to set it to true as shown below.

      JLabel lb = new JLabel("Test");      lb.setBackground(Color.red);      lb.setOpaque(true); <--This line of code must be set to true or otherwise the 

From the JavaDocs

setOpaque

public void setOpaque(boolean isOpaque)  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.  The default value of this property is false for JComponent. However,   the default value for this property on most standard JComponent subclasses    (such as JButton and JTree) is look-and-feel dependent.Parameters:isOpaque - true if this component should be opaqueSee Also:isOpaque()