java 为什么我的 JFrame 不显示?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3808221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:27:30  来源:igfitidea点击:

Why is my JFrame not showing?

javaswing

提问by Dave

I'm pretty sure I've done it this way before, but for some reason, the JFrame won't show up when I run it.

我很确定我以前这样做过,但是由于某种原因,当我运行它时 JFrame 不会出现。

    JLabel originalString =  new JLabel("Original String: " 
                                        + str.getMutator());
    JLabel currentString = new JLabel("Current String: " 
                                      + str.getMutator());
    JLabel finalString =  new JLabel("Final String: " + str.getTarget());

    JPanel panel = new JPanel();
    panel.add(originalString);
    panel.add(currentString);
    panel.add(finalString);

    JFrame frame = new JFrame("Mutating String!");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
}

回答by Sheng Chien

Try to set size or check with the preferred size of your components probably because you call pack().

尝试设置大小或检查组件的首选大小,这可能是因为您调用了 pack()。

frame.setSize(x, y);

frame.setSize(x, y);

回答by Colin Hebert

Your problem must be somewhere else (is the method called does it throw an exception ?) because your code works (I commented the str calls) :

你的问题一定在其他地方(被调用的方法是否抛出异常?)因为你的代码有效(我评论了 str 调用):

http://img217.imageshack.us/img217/902/screenvlg.png

http://img217.imageshack.us/img217/902/screenvlg.png

import javax.swing.*;
public class Test{
    public static void main(String... args){
        JLabel originalString =  new JLabel("Original String: " /*+ str.getMutator()*/);
        JLabel currentString = new JLabel("Current String: "/* + str.getMutator()*/);
        JLabel finalString =  new JLabel("Final String: " /* + str.getTarget()*/);

        JPanel panel = new JPanel();
        panel.add(originalString);
        panel.add(currentString);
        panel.add(finalString);

        JFrame frame = new JFrame("Mutating String!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}