Java Swing:主类等到JFrame关闭

pip*_*ips 4 java swing input jframe invokeandwait

我需要一些简单的java应用程序的帮助,它使用两个jframe来获取一些输入参数.这是我的代码草图:

//second jframe, called when the button OK of the first frame is clicked
public class NewParamJFrame extends JFrame{
  ...
}

//first jframe
public class StartingJFrame extends JFrame{
  private static  NewParamJFrame newPFrame = null;
  private JTextField gnFilePath;
  private JButton btnOK;

  public StartingJFrame(){
            //..
    initComponents();
  }

  private void initComponents(){
     btnOK.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        try{
        EventQueue.invokeAndWait(new Runnable(){
           public void run() {
               try {
               newPFrame = new NewParamJFrame();
               newPFrame.setVisible(true);
               } catch (Exception e) {
               e.printStackTrace();
               }
           }
         });
        }
        catch(InvocationTargetException e2) {} 
        catch(InterruptedException e1){}
        dispose();
      }
  }

  public String getText(){
       return gnFilePath.getText();
  }
}

public class Main {
  private static StartingJFrame begin = null;
  public static void main(String[] args) {
     try{
        EventQueue.invokeAndWait(new Runnable(){
            public void run() {
                try {
                    begin = new StartingJFrame();
                    begin.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    catch(InvocationTargetException e) {} 
    catch(InterruptedException e1){}

    String s= begin.getText();

    //...use s ...
  }
}
Run Code Online (Sandbox Code Playgroud)

对getText()的调用会导致NullPointerException.我希望主类等到帧关闭但我不知道该怎么做.我第一次使用秋千.

dic*_*c19 6

我希望主类等到帧关闭但我不知道该怎么做.我第一次使用秋千.

如果我正确理解您的问题,您需要StartingJFrame等待直到NewParamJFrame关闭然后继续执行.如果是这种情况,则不会发生因为JFrame不支持模态.但是JDialog,所以你可以只有一个JFrame并在JDialog其父元素中执行参数请求JFrame.

有关模态的更好解释,请阅读如何在对话框中使用.

请参阅此主题:使用多个JFrame,好/坏练习?

在任何情况下,您可能都会遇到一个新问题:JFrame如果用户在没有输入任何参数的情况下关闭/取消对话框应该怎么做?怎么会JFrame知道对话中刚刚发生了什么?在这个答案中描述了一种方法.您将看到示例是关于登录对话框,但问题与此类似:如何通过对话框通知其父框架进程如何进行?


Hol*_*ger 5

在不修改代码流的情况下等待关闭的最简单方法是使用 modal JDialog。因此,您必须更改您的StartingJFrame类以使其成为JDialog而不是的子类JFrame,并将以下内容添加到其构造函数的开头:

super((Window)null);
setModal(true);
Run Code Online (Sandbox Code Playgroud)

然后实例setVisible(true);上的调用StartingJFrame将等到对话框关闭,因此invokeAndWait调用也将等待。