简体   繁体   中英

jLabel.setOpaque(true) does not work

I have a jLabel which initially has setOpaque set to false by default. When I set the back ground color of the label to some color and set the setOpaque to true it does not show up the color. Why is it not displaying the color even though the setOpaque is being set to ture?

Here is what I'm trying to do.

JLabel key = values[i];
key.setBackground(Color.red);
key.setOpaque(true);

Works like a charm for me:

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class TestJLabel {

    protected void initUI() {
        JFrame frame = new JFrame(TestJLabel.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel key = new JLabel("Some opaque label with a yellow background.");
        key.setBackground(Color.YELLOW);
        key.setOpaque(true);
        frame.add(key);
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestJLabel().initUI();
            }
        });
    }

}

Resulting in:

在此输入图像描述

Try like this:-

JLabel key = values[i];
key.setOpaque(true);
key.setBackground(Color.red);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM