从标题可以看出,我无法设置JLabel
的背景色。有人能帮帮我吗?
package pl.maciekfruba;
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame f = new JFrame("Message");
JPanel p = new JPanel();
JLabel l = new JLabel("Some text");
BorderLayout bl = new BorderLayout();
Font font = new Font("Impact", Font.PLAIN, 30);
l.setBackground(Color.RED);
l.setFont(font);
l.setOpaque(true);
p.add(l);
f.add(p, BorderLayout.LINE_START);
f.setLayout(bl);
f.setSize(new Dimension(1000, 600));
f.setVisible(true);
}
}
我试着调用setOpaque(true)
方法,但它仍然不工作。
最好从事件调度线程(EDT)启动gui,因此:
package pl.maciekfruba;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Color;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
public class Main extends JFrame {
private void setGui() {
try {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel();
JLabel l = new JLabel("Some text");
Font font = new Font("Impact", Font.PLAIN, 30);
l.setBackground(Color.RED);
l.setFont(font);
l.setOpaque(true);
p.add(l);
add(p, BorderLayout.LINE_START);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
EventQueue.invokeAndWait(() -> {
Main f = new Main();
f.setGui();
f.setSize(1000, 1000);
f.setVisible(true);
});
} catch (Exception e) {
e.printStackTrace();
}
}
}