JavaFX – how to focus on one phase
My application has a main application stage from which a second window can be opened I just want to focus on one stage
I have two problems to solve:
1 – how to focus only on the second stage (filechooser opendialog)? That is, I cannot switch to the main application phase until the user clicks "open" or "Cancel"
2 – how can I get the user to close the second stage before closing the main stage?
Now I can close the main window while the second phase (opendialog) is still running
thank you.
Solution
You can use a combination of modality and ownership phases
subStage. Initowner (stage) – > ensure that the sub station moves with its owner
subStage. Initmodality (modality. Window_modal) – > ensure that the subdirectory prevents input events from being passed from its owner (parent) to its root directory to all windows
If you want to block input events from all windows of the same application, you can also use modify APPLICATION_ Modal, except for windows from its sub hierarchy
Dialog adopts mode and blocking mode by default The default mode of dialog is modification APPLICATION_ Modal, to which you can add initowner (...)
Note: you cannot apply the above rules to filechooser However, you can use showopendialog (window ownerwindow)
fileChooser.showOpenDialog(stage);
Complete example
import javafx.application.Application; import javafx.stage.Modality; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage stage) { stage.setTitle("Main Stage"); stage.setWidth(500); stage.setHeight(500); stage.show(); Stage subStage = new Stage(); subStage.setTitle("Sub Stage"); subStage.setWidth(250); subStage.setHeight(250); subStage.initOwner(stage); subStage.initModality(Modality.WINDOW_MODAL); subStage.show(); } public static void main(String[] args) { launch(args); } }