JLabel.setBackground(颜色)不起作用?

时间:2013-01-28 18:58:13

标签: java swing colors

在此SSCCE代码中:

此方法有效

label.setForeground(Color.GREEN);

但是下一个方法不起作用!

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();

            }
        });
    }
}

2 个答案:

答案 0 :(得分:34)

组件必须是不透明的,因为它的背景才有效,JLabel的默认值是false,所以你必须设置它:

label.setOpaque(true);

答案 1 :(得分:4)

您需要先将标签设置为不透明。否则,它不会被涂上。  请看:How do I set a JLabel's background color?