如何在关闭JavaFX舞台后停止WebEngine?

4

当我使用WebEngine创建一个从YouTube播放视频的新舞台后,关闭它后YouTube仍然在后台播放。如果我使用“Platform.exit”,它将关闭所有JavaFX应用程序,但我只想关闭为YouTube创建的舞台。

这是我的YouTube播放器类:

public class YouTube_player  {
    public YouTube_player(String url) {
        final Group root = new Group();
        Scene scene = new Scene(root, 820, 480);

        final Stage stage = new Stage();
        final WebView webView = new WebView();
        final WebEngine webEngine = webView.getEngine();
        webEngine.loadContent(url);
        root.getChildren().add(webView);
        stage.centerOnScreen();

        stage.setScene(scene);
        stage.show();
        stage.setOnCloseRequest(new EventHandler<WindowEvent>(){

            @Override
            public void handle(WindowEvent event) {
              //What i should put here to close only this stage.
              //Platform.exit - closes all my stages.
              //webEngine.getLoadWorker().cancel(); - dont stop Youtube )))
            }
        });

    }
}

当我在'mainstage'中点击按钮后,我的Youtube播放器舞台被创建:

b1.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent event) {
        new YouTube_player(url_video_p1);
    }
});
2个回答

5

你无法处理WebEngine对象,唯一可以做的是将WebEngine内容设置为null

webView.getEngine().load(null);


如果WebEngine陷入JS循环,则此方法无效。有没有办法停止ScriptEngine的运行? - Frederic Leitenberger
@Frederic Leitenberger 你尝试过使用事件处理程序或CountdownLatch来终止循环吗?Platform.exit()怎么样? - Andrew Scott Evans
Platform.exit() 不起作用,因为它会关闭整个子系统。所以当你仍然想在其他窗口/视图中使用它时,就不能这样做。没有重新启动 JVM,无法从 Platform.exit() 中恢复。 - Frederic Leitenberger
@AndrewScottEvans 我不知道 CountdownLatch 如何停止 JS 脚本(这是 VM 代码)。至于“杀死循环” - 我也不知道怎么做...我所知道的唯一方法是中断或终止线程,但这可能也不可行,或者会导致其他不良副作用。 - Frederic Leitenberger
有一件事(我之前注意到)与此相关:似乎任何JS脚本在10秒后都会被静默停止(无论如何)。但这对于这里来说并没有太大用处。当尝试显示新内容时,“等待10秒”听起来不合理。而且它静默停止脚本的事实也是不合理的。它至少应该记录一些东西和/或有一个设置来控制它。 - Frederic Leitenberger
@Frederic Leitenberger http://www.java67.com/2015/07/how-to-stop-thread-in-java-example.html - Andrew Scott Evans

1
Java 9,对我来说可行:
webView.getEngine().load("");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接