JavaFX 2.0: Closing a stage (window)

99封情书 提交于 2019-11-27 01:16:04

问题


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!


回答1:


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.




回答2:


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

((Node)(event.getSource())).getScene().getWindow().hide();



回答3:


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));


来源:https://stackoverflow.com/questions/10212366/javafx-2-0-closing-a-stage-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!