我尝试使用此代码来显示带标签的窗口,但它只显示一个空白窗口。
JFrame window = new JFrame("My Window");
window.setVisible(true);
window.setResizable(true);
window.setSize(680,420);
window.setContentPane(new Container());
window.getContentPane().setLayout(new FlowLayout());
JPanel panel = new JPanel();
JLabel label = new JLabel("LABEL");
label.setBackground(Color.BLACK);
panel.add(label);
window.add(panel);
最佳答案
尝试最后调用setVisible
JFrame window = new JFrame("My Window");
//window.setVisible(true);
//window.setResizable(true);
//window.setSize(680,420);
//window.setContentPane(new Container());
window.setLayout(new FlowLayout());
JPanel panel = new JPanel();
JLabel label = new JLabel("LABEL");
label.setBackground(Color.BLACK);
panel.add(label);
window.add(panel);
window.setResizable(true);
// Pack will size the window to fit the content,
// tacking into account the preferred size of the
// content...
window.pack();
window.setVisible(true);
另请注意,JLabel
默认情况下是透明的,因此设置其背景颜色不会产生任何效果,除非将其 opaque
属性更改为 true
关于java - 如何在 JFrame 中显示 JButton 和 JLabels?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22317327/