为什么我的舞台在程序运行时没有反应? (java fx)
问题描述:
我有一个简单的javaFx应用程序,它是从html结构中搜索一些文本和一些元素。它有一个小窗口,一个舞台。程序可以正常运行,但程序运行时,阶段(javaFx窗口)不响应,它会冻结。 我以为我应该在一个新的线程中运行我的舞台,但它没有奏效。这是我程序中提到的部分。 如何在没有窗口冻结的情况下运行我的程序?为什么我的舞台在程序运行时没有反应? (java fx)
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(...)
中。参见例如Using threads to make database requests了解JavaFX中多线程的更长解释。
谢谢,它的工作! :) – Kovoliver