JavaFX 2.0: Closing a stage (window)

2019-01-17 06:32发布

I'm making a application in JavaFX 2.0. From my main window I am starting a new window with some settings. After I am done adjusting the settings I want to press a button like "Save changes".

I would like this button to save the changes and close the window. By closing i mean killing it, not placing it in the background or setting the visibility. I've read about a method Stage.close()

http://docs.oracle.com/javafx/2.0/api/javafx/stage/Stage.html

As you can see it's similar to the method Hide(), which only hides the window, not closing it.

Q: Anybody knows any methods or have some code that would help me close a window?

All help will be greatly appreciated. Thanks!

标签: javafx stage
3条回答
聊天终结者
2楼-- · 2019-01-17 06:57

This worked perfectly for me (with the import for Node):

((Node)(event.getSource())).getScene().getWindow().hide();
查看更多
冷血范
3楼-- · 2019-01-17 06:58

For the users also interested in listening to the close window event, add an event filter to the window: (this event is also fired when the user press the OS close button of the application)

    yourWindow.addEventFilter(WindowEvent.WINDOW_CLOSE_REQUEST, event -> {
        // add your code here to handle the close event
        // use event.consume(); to prevent the application from closing
    });

If you need to close the application with a custom close button, in the onAction method of the button fire the event :

 yourWindow.fireEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSE_REQUEST));
查看更多
放荡不羁爱自由
4楼-- · 2019-01-17 07:18

The documentation you linked states that stage.close():

Closes this Stage. This call is equivalent to hide().

As hide() is equivalent to close() and close() closes the stage, then hide() also closes the stage.

When all stages in an application are hidden (or closed if you like, because it is the same thing), the application exits. Confusing, I know, but that's just the way the JavaFX team decided to name and implement the actions.

If desired, the Platform.setImplicitExit(boolean) method can be used to switch off the default behaviour of exiting the application when the last window is closed or hidden.

查看更多
登录 后发表回答