首页 > 编程 > Java > 正文

JavaFX 监听窗口关闭事件实例详解

2019-11-26 12:12:59
字体:
来源:转载
供稿:网友

1.写在前面

在JavaFX的程序开发的时候,在使用多线程的时候,默认情况下在程序退出的时候,新开的线程依然在后台运行。

在这种情况下,可以监听窗口关闭事件,在里面关闭子线程。

2.具体实现的样例

package sample;import javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.event.EventHandler;import javafx.fxml.FXMLLoader;import javafx.scene.Parent;import javafx.scene.Scene;import javafx.stage.Stage;import javafx.stage.WindowEvent;public class Main extends Application {  @Override  public void start(Stage primaryStage) throws Exception{    Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));    primaryStage.setTitle("Hello World");    primaryStage.setScene(new Scene(root, 300, 275));    primaryStage.show();    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {      @Override      public void handle(WindowEvent event) {        System.out.print("监听到窗口关闭");      }    });  }  public static void main(String[] args) {    launch(args);  }}

其中,这个就是具体监听窗口关闭的具体实现:

   primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {      @Override      public void handle(WindowEvent event) {        System.out.print("监听到窗口关闭");      }    });

3.效果

在点击窗口关闭按钮的时候,控制台会输出

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表