2018년 3월 9일 금요일

[JavaFX] How to get window exit event in JavaFX (윈도우 종료 이벤트 처리)


Insert below source code in the start() function of main class.
메인 클래스의 start() 함수내에 다음 코드를 삽입하여, 종료 이벤트를 받아서 처리할 수 있다.
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    public void handle(WindowEvent we) {
        //TODO: Save working data
        System.exit(0);
    }
});   

Java 8 lambda expression
stage.setOnCloseRequest((WindowEvent we) -> {
    //TODO: Save working data
    System.exit(0);
}); 

1. Full Source (Line 17~22)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package bloggerpostsnippet;

import javafx.application.Application;
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 BloggerPostSnippet 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.setOnCloseRequest(new EventHandler<WindowEvent>() {
            public void handle(WindowEvent we) {
                //TODO: Save working data
                System.exit(0);
            }
        });           
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }    
}


2. Lambda Expression (Line 18)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package bloggerpostsnippet;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

public class mainExitEvent 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.setOnCloseRequest((WindowEvent we) -> {
            //TODO: Save working data
            System.exit(0);
        });        
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}





댓글 없음:

댓글 쓰기