-3

Whenever I use the following method, I receive:

Exception in thread "JavaFX Application Thread" java.lang.IllegalStateException: Not on FX application thread; currentThread = JavaFX Application Thread

I don't understand how to implement runnable to solve it.
All I want is to use JavaFX, select file/directory and get the string to the selected file/directory -> then I open new stages.

private static String strSelectDirectory(int intFileType)
{
    String strResult="";
        Stage stage = new Stage();
        File fileDefaultDir = new File(System.getProperty("user.dir")); //Default directory of selection
        if(intFileType==0)                                              //Select File
        {
            FileChooser fileChooser = new FileChooser();                //define file chooser
            fileChooser.setInitialDirectory(fileDefaultDir);            //define default/starting directory
            File selectedFile = fileChooser.showOpenDialog(stage);      //open filedialog and select file
            strResult=selectedFile.getPath();
        } else if(intFileType==1)                                               //Select Directory
        {
            DirectoryChooser directoryChooser = new DirectoryChooser();         //define directory chooser
            directoryChooser.setInitialDirectory(fileDefaultDir);               //define default/starting directory
            File selectedDirectory = directoryChooser.showDialog(stage);        //open filedialog and select directory
            strResult=selectedDirectory.getAbsolutePath();
        }
        stage.close();
    return strResult;
}
Hronic
  • 155
  • 1
  • 1
  • 7

1 Answers1

0

Instances of Runnable create "runnable" blocks of code to be executed on a thread. By definition, different thread from the one named JavaFX Application Thread.

In short, JavaFX relies on its own thread structure to update its graphic co-routine, therefore any code which interacts with components that deal with graphics, must be executed inside the JavaFX platform's compliant logical end-points.

Use Platform.runLater( () ->{ /*your code here*/ }); to inject logic wihch affects UI components.

This effectively creates a logical hook which executes your code in the JavaFXThread construct as part of it's graphics update subroutine.

This also affects all logical routines which handle window content or window objects (stages).

Lastly, make sure you use Platform.exit() whenever you effectively want to close your application, or you will have hanging, immortal instances of the JVM which will never close.

EverNight
  • 964
  • 7
  • 16