Use a thread to wait until the user has picked a file

蓝咒 提交于 2020-01-16 14:35:06

问题


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.

Here is the skeleton code:

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
}

回答1:


OK, Two things.

You don't need multiple threads

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

    }
}

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.

If you do need threads (you know, for something else)

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.



来源:https://stackoverflow.com/questions/26921142/use-a-thread-to-wait-until-the-user-has-picked-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!