Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a JLabel's background color?

Tags:

java

swing

jlabel

People also ask

How do I change the background color of a label in NetBeans?

So, let's first see this is done on NetBeans IDE using the JFrame Form file. Firstly, drag a JLabel from the palette on to the JFrame. Then select the JLabel and go to the Properties window on the bottom right corner. There you will see Background property then choose the desired color.

How do I change the background of a JFrame?

In general, to set the JFrame background color, just call the JFrame setBackground method, like this: jframe. setBackground(Color. RED);

How do I change the color of a Jbutton in Java?

Normally with Java Swing you can set the background color of a button with: myJButton. setBackground(Color. RED);


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 opaque
See Also:
isOpaque()

For the Background, make sure you have imported java.awt.Color into your package.

In your main method, i.e. public static void main(String[] args), call the already imported method:

JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);

NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.