【问题标题】:Use a thread to wait until the user has picked a file使用线程等待用户选择文件
【发布时间】:2014-11-14 00:43:17
【问题描述】:

我在 Java 中有一个 mainClass,它可以启动一个 GUI。我要求用户使用 JFileChooser 打开一个文件。我希望 main 等到用户完成选择文件,然后继续 main 中的其余代码。我如何使用线程来做到这一点?提前致谢。

这是骨架代码:

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
}

【问题讨论】:

  • 简短回答,不要。 Swing 不是线程安全的,这意味着您应该只在 Event Dispatching Thread 的上下文中更新 UI。有关模式详细信息,请参阅Concurrency in SwingJFileChooser 显示一个模态对话框,这意味着在用户关闭它之前,代码将在该点阻塞...
  • 这个问题的措辞让我很困惑。您是否真的想使用单独的线程等到用户进行选择(不确定这将如何工作),或者您想在选择文件后使用单独的线程来做某事?这很微妙,但很重要。

标签: java multithreading swing jfilechooser


【解决方案1】:

好的,两件事。

您不需要多个线程

问题是,您只需使用模态对话框即可完成等待用户选择文件的目标。它的工作原理如下:

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。

如果你确实需要线程(你知道,为了别的)

Swing 使用它所谓的Event Dispatch Thread。如评论中所述,Swing 不是线程安全的。这意味着任何和所有对 Swing 组件的方法调用都应该从 EDT 完成。您可以使用SwingUtilities.invokeLater(Runnable) 安排代码在 EDT 上运行。您可以使用Swing Worker 安排在后台线程中运行(使用线程池)。您的大部分代码可能只会在 EDT 上运行。可以使用 swing worker 将长时间运行的操作发送到后台线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 2012-11-25
    • 1970-01-01
    • 2012-02-18
    • 2023-03-14
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多