为什么我的JFrame没有显示?

时间:2010-09-27 21:56:55

标签: java swing

我很确定我之前已经这样做了,但出于某种原因,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);
}

2 个答案:

答案 0 :(得分:4)

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

frame.setSize(x,y);

答案 1 :(得分:3)

您的问题必须在其他地方(这个方法是否会引发异常?)因为您的代码有效(我评论了str调用):

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);
    }
}