使用线程等待用户选择文件 [英] Use a thread to wait until the user has picked a file

查看:93
本文介绍了使用线程等待用户选择文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java中的mainClass,它可以启动一个GUI.我要求用户使用JFileChooser打开文件.我希望main一直等到用户完成选择文件后,再继续main中的其余代码.我该如何使用线程?预先感谢.

I have a mainClass in Java, that starts a GUI in swing. I ask the user to open a file using a JFileChooser. I want the main to wait until the user has finished picking the file and then continue with the rest of the code in main. How do I do this using threads? Thanks in advance.

这是基本代码:

public class MainClass {
    public static void main(String[] args) {

        GUI gui= new GUI();
        //wait for user input here

        //Continue with code
        System.out.println("User has picked a file");
    }
}

GUI.java

public class GUI{
   //User picks file using JFileChooser
   JFileChooser chooseFile= new JFileChooser();
   //Notify mainclass we're done with fiction to continue with code
}

推荐答案

好,两件事.

问题是,您可以简单地通过使用模态"对话框来完成等待用户选择文件的目标.可以像下面这样工作:

The thing is, you can accomplish your goal of waiting for a user to select a file simply by using a Modal dialog. This works about like the following:

import javax.swing.*;

public class DialogTest {

    public static void main(String[] args) {
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        System.out.println("File chooser is now closed. File is: " + 
                chooser.getSelectedFile().toString());

    }
}

在用户选择文件,单击取消"或单击X之前,showOpenDialog方法将不会返回.请注意,如果用户取消,getSelectedFile()将返回null.

The showOpenDialog method will not return until the user has either selected a file, clicked cancel, or else clicked the X. Just be aware that getSelectedFile() will return null if the user cancels.

Swing使用其所谓的事件调度线程.如注释中所述,Swing不是线程安全的.这意味着对Swing组件的所有方法调用都应从EDT中完成.您可以使用SwingUtilities.invokeLater(Runnable)计划在EDT上运行的代码.您可以使用

Swing uses what it calls the Event Dispatch Thread. Swing is not thread safe, as mentioned in the comment. What this means is that any and all method calls to Swing components should be done from the EDT. You can schedule code to be run on the EDT by using SwingUtilities.invokeLater(Runnable). You can schedule something to run in a background thread (using a thread pool) by using a Swing Worker. Most of your code will probably just run on the EDT. Long-running operations can be sent to a background thread using swing workers.

这篇关于使用线程等待用户选择文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆