lördag 3 december 2011

JavaFX 2.0 - How to close your windows

Default when you close a window in JavaFX2 the window is disposed, and if it is your parent window the system is going to shutdown. In Swing this behavior is controlled by the setDefaultCloseOperation()or a WindowListener. In this post we are going to see how this can be controlled in JavaFX2.

By default when you click the "close cross" in your window the application will shutdown and call the stop() function which you can override in your application. This behavior can be changed by using the WindowEvent which will be created.

Let us see an example:

public class ClosingDemo extends Application implements EventHandler<WindowEvent> {
  public void start(Stage stage) throws Exception {

  public void stop() throws Exception {
    System.out.println("Stopping: stop()";);
  public void handle(WindowEvent event) {
    System.out.println("Stopping: handle()");
As you can see, we implement the interface EventHandler and assign it to our stage. When we later press the "close cross" a event will be created and passed to our EventHandler. Now we can change the behavior of the application. Maybe we like to prevent the application from closing. In that case we can use the consume() function of the WindowEvent. This will consume the event and prevent the window from closing.

This was a short introduction of how you can change the behavior of the closing operation in your application. For more informational I recommend you to have a look in the API for the WindowEvent.

Inga kommentarer:

Skicka en kommentar