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



我有一个简单的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.");
}

在后台线程中运行需要很长时间(大概是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;如果修改,则需要将修改 UI 的代码包装在Platform.runLater(...)中。例如,请参阅使用线程发出数据库请求,以获取有关 JavaFX 中多线程的较长解释。

最新更新