【问题标题】:Why is my frame empty when I run? [duplicate]为什么我跑步时框架是空的? [复制]
【发布时间】:2015-11-14 18:32:50
【问题描述】:

当我运行这段代码时:

public class Menu extends JFrame implements ActionListener {


JLabel logo = new JLabel("MyChef");

JPanel north = new JPanel();

public void main(String args[]){
new Menu();
}

Menu(){
JFrame frame = new JFrame();

frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setTitle("MyChef");
frame.setSize(500, 300);
frame.setVisible(true);
frame.setResizable(false);

frame.add(north, BorderLayout.NORTH);
north.add(logo);

}

public void actionPerformed(ActionEvent e){

}
}

窗口打开,但没有显示任何内容...我的标签在哪里?我很迷茫,因为我以前做过各种 GUI,要么我很愚蠢,要么我不知道!对不起,如果这是一个愚蠢的问题,我只是被困住了,我不得不发布这个。

【问题讨论】:

  • A common problem -- 提问前先搜索一下网站,很快就能找到解决办法。

标签: java swing


【解决方案1】:

您的代码适用于我,但我认为它不适用于您,因为您在设置框架可见后添加了一个组件。 之后

致电frame.setVisible(true)(和setSize
frame.add(north, BorderLayout.NORTH);
north.add(logo);

所以你的代码应该是这样的(格式也正确):

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Menu extends JFrame implements ActionListener {

    JLabel logo = new JLabel("MyChef");

    JPanel north = new JPanel();

    public static void main(String args[]) {
        new Menu();
    }

    public Menu() {

        JFrame frame = new JFrame();

        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setTitle("MyChef");
        frame.setResizable(false);

        frame.add(north, BorderLayout.NORTH);
        north.add(logo);

        frame.setSize(500, 300);
        frame.setVisible(true);

    }

    public void actionPerformed(ActionEvent e) {

    }
}

【讨论】:

  • 谢谢!啊哈成功了!你刚刚把我从自我毁灭中救了出来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 2014-04-03
  • 2018-07-22
  • 2016-06-10
相关资源
最近更新 更多