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.效果
在點擊窗口關閉按鈕的時候,控制台會輸出

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!