Wait for selectFolder()

I am writing a program to do mass image editing and would like to have the end user select an input and output folder when the program starts.

I tried using selectFolder("Select a input folder:", "inputFolder"); and it opened the folder selection thing, but my code continues to run before a folder is selected, leading to a null error where one of my commands tries acting on the not yet initiated String iPath

Minimized code example:
import java.io.File;

String inputPath;

void setup() {
  selectFolder("Select a input folder:", "inputFolder");
  
  CommandIWantToRunAFTERFolderIsSelected(inputPath);
}

void inputFolder(File selection) {
  if (selection == null) {
    javax.swing.JOptionPane.showMessageDialog(null, "Input Window was closed or the user hit cancel.", "Error", javax.swing.JOptionPane.ERROR_MESSAGE);
    exit();
  } else {
    inputPath = selection.toString();
    println("User selected " + selection.getAbsolutePath());
  }
}

void CommandIWantToRunAFTERFolderIsSelected(String path){
  if (path == null){
    println("Process crash due to null interperetation");
  } else {
    println("no crash as command ran after string initiated");
  }
}

Running the above code without modification, you will see that the command that interprets the path runs before a file path is selected.

How would I fix this issue

1 Like

Basically in setup () have only size and SelectFolder

In draw() do what you want to achieve but with an if clause around it like if(ipath!=null) {

1 Like

Prior to PS3 the select???? methods were modal i.e. blocked the main thread (which how Java) works. In pS3 the Processing developers changed it so that they are executed on a separate thread it means the main thread no longer stops.
There is no option in Processing to make them behave modally so you have 3 options

  1. Simply test the reference and only use the selected folders when they are not null i.e.
    if(inFolder != null){
      // safe to use inFolder
    }
  1. Write your own code to access the Java Swing file dialog boxes
  2. Use the equivalent functions in G4P because they are modal. I added these when PS3 was released.
2 Likes
String inputPath;

void setup() {
  selectFolder("Select an input folder:", "inputFolder");

  while (inputPath == null)  delay(1);

  CommandIWantToRunAFTERFolderIsSelected(inputPath);
}
2 Likes

I really like this solution to the problem, but I marked @quark’s reply to the solution as it gave multiple, general solutions.

1 Like