Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JLabel.setBackground(Color color) doesn't work?

Tags:

java

colors

swing

In this SSCCE code:

This method work

label.setForeground(Color.GREEN);

But this next method doesn't work!

label.setBackground(Color.BLUE);

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

public class LabelColorTest extends JPanel
{

    static JLabel label;
    JPanel panel;

    public LabelColorTest()
    {
        label = new JLabel();
        label.setVerticalAlignment(JLabel.CENTER);
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setText("Hello world");

        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(label, BorderLayout.CENTER);

        label.setForeground(Color.GREEN);  //HERE
        label.setBackground(Color.BLUE);  //HERE


        this.setLayout(new BorderLayout());
        this.add(panel);
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Hellow world");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 250);
        frame.add(new LabelColorTest(), BorderLayout.CENTER);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();

            }
        });
    }
}
like image 366
Saleh Feek Avatar asked Jan 28 '13 18:01

Saleh Feek


People also ask

How do I change the background color of a label?

To change the label's base background color, right click on a label against a patterned background, and select your choice from the Label Background menu.

How do I change the color of my JPanel?

We can set a background color to JPanel by using the setBackground() method.


1 Answers

A component must be opaque for its background do be effective, a JLabel's default is false, so you have to set it:

label.setOpaque(true);
like image 189
kleopatra Avatar answered Sep 30 '22 16:09

kleopatra