1

I have a simple javaFx application which is search some text and some elements from html structures. It has a little window, a stage. The program can run correctly, but while the program is running, the stage (javaFx window) does not respond, it freeze. I thought I should run my stage in a new thread, but it didn't work. This is my program's mentioned part. How can I run my program without window freeze?

public class Real_estate extends Application implements Runnable {
    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
        stage.getIcons().add(new Image("http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/house-icon.png"));
        stage.setTitle("Simple program 0.8");
        stage.setWidth(300);
        stage.setHeight(300);
        stage.setResizable(false);

        HtmlSearch htmlSearch = new HtmlSearch ();
        htmlSearch .toDatabase("http://example.com");

    }

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void run() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
JFPicard
  • 5,029
  • 3
  • 19
  • 43
Kovoliver
  • 238
  • 2
  • 13

1 Answers1

4

Run the code that takes a long time to run (presumably htmlSearch.toDatabase(...)) in a background thread. You can do this with

public class Real_estate extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
        stage.getIcons().add(new Image("http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/house-icon.png"));
        stage.setTitle("Simple program 0.8");
        stage.setWidth(300);
        stage.setHeight(300);
        stage.setResizable(false);

        HtmlSearch htmlSearch = new HtmlSearch ();
        new Thread(() -> htmlSearch.toDatabase("http://example.com")).start();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

This assumes that htmlSearch.toDatabase(...) does not modify the UI; if it does, you will need to wrap the code that modifies the UI in Platform.runLater(...). See, e.g. Using threads to make database requests for a longer explanation of multithreading in JavaFX.

James_D
  • 201,275
  • 16
  • 291
  • 322