java - 如何在 JFrame 中显示 JButton 和 JLabels?

标签 java swing layout jframe jlabel

我尝试使用此代码来显示带标签的窗口,但它只显示一个空白窗口。

    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/

相关文章:

java - 从 JSONPath 数组的不同对象中查询具有特定值的键

java - Jtable 在同一行左右对齐文本

css - 在 css 中将 float 定义为中心

java - android 维基百科 api 游戏

Android 布局 - 图片占用额外空间

java - java中如何让线程等待并通知

java - AsyncTask.execute() 并更改 UI

java - 带有 cookie 的数字格式异常 JSP 页面

java - PaintComponent 和 java 图形

java - 布局完成后调用的方法?