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();
}
});
}
}
组件必须是不透明的,因为它的背景有效,JLabel的默认值为false,因此您必须设置它:
label.setOpaque(true);
You will need to set the label to opaque first. Else, it wont be painted. Look at: How do I set a JLabel's background color?
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.