为什么我的舞台在程序运行时没有响应? (java fx)

时间:2017-08-04 17:26:18

标签: java javafx freeze stage

我有一个简单的javaFx应用程序,它搜索一些文本和一些来自html结构的元素。它有一个小窗口,一个舞台。该程序可以正常运行,但在程序运行时,阶段(javaFx窗口)不响应,它冻结。 我以为我应该在一个新的线程中运行我的舞台,但它没有工作。这是我提到的程序部分。 如何在没有窗口冻结的情况下运行我的程序?

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.");
    }

1 个答案:

答案 0 :(得分:4)

在后台线程中运行需要很长时间才能运行的代码(大概是htmlSearch.toDatabase(...))。您可以使用

执行此操作
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);
    }
}

这假定htmlSearch.toDatabase(...)不修改UI;如果是,则需要在Platform.runLater(...)中包装修改UI的代码。见,例如, Using threads to make database requests有关JavaFX中多线程的更长解释。