【问题标题】:Why my stage doesn't respond while the program is running? (java fx)为什么我的舞台在程序运行时没有响应? (Java 外汇)
【发布时间】:2018-01-12 17:24:22
【问题描述】:

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

【问题讨论】:

    标签: java javafx freeze stage


    【解决方案1】:

    在后台线程中运行需要很长时间才能运行的代码(大概是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 中的多线程的说明。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      相关资源
      最近更新 更多