java - Use a thread to wait until the user has picked a file -
i have mainclass in java, starts gui in swing. ask user open file using jfilechooser. want main wait until user has finished picking file , continue rest of code in main. how do using threads? in advance.
here skeleton code:
public class mainclass { public static void main(string[] args) { gui gui= new gui(); //wait user input here //continue code system.out.println("user has picked file"); } }
gui.java
public class gui{ //user picks file using jfilechooser jfilechooser choosefile= new jfilechooser(); //notify mainclass we're done fiction continue code }
ok, 2 things.
you don't need multiple threads
the thing is, can accomplish goal of waiting user select file using modal dialog. works 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 closed. file is: " + chooser.getselectedfile().tostring()); } }
the showopendialog
method not return until user has either selected file, clicked cancel, or else clicked x. aware getselectedfile()
return null if user cancels.
if need threads (you know, else)
swing uses calls event dispatch thread. swing not thread safe, mentioned in comment. means , method calls swing components should done edt. can schedule code run on edt using swingutilities.invokelater(runnable)
. can schedule run in background thread (using thread pool) using swing worker. of code run on edt. long-running operations can sent background thread using swing workers.
Comments
Post a Comment