JavaFX2: Closing a stage (sub-floor) from within itself

I am new to JavaFx and I am building an application and need something similar to the JDialog that was suggested when using swing components. I solved this by creating a new stage, but now I need a way to close the new stage from the inside by pressing a button. (yes, the x button also works, but it is also needed on the button). To describe the situation: I have a main class from which I create a main scene with a scene. For this I use FXML.

public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Builder.fxml"));
    stage.setTitle("Ring of Power - Builder");
    stage.setScene(new Scene(root));
    stage.setMinHeight(600.0);
    stage.setMinWidth(800.0);
    stage.setHeight(600);
    stage.setWidth(800);
    stage.centerOnScreen();
    stage.show();
}

Now in the main window that appears, I have all the controls and menus and stuff created through FXML and the corresponding control class. This is the part in which I decided to include "About Information" in the "Help" menu. So, I have an event when the Help - About menu is activated, for example:

@FXML
private void menuHelpAbout(ActionEvent event) throws IOException{
    Parent root2 = FXMLLoader.load(getClass().getResource("AboutBox.fxml"));
    Stage aboutBox=new Stage();
    aboutBox.setScene(new Scene(root2));
    aboutBox.centerOnScreen();
    aboutBox.setTitle("About Box");
    aboutBox.setResizable(false);
    aboutBox.initModality(Modality.APPLICATION_MODAL); 
    aboutBox.show();
}

, About Box FXML . , , , , aboutBox AboutBox.java, .

, , - public static Stage aboutBox; Builder.java AboutBox.java, . - . ?

.

+5
2

, , .

new EventHandler<ActionEvent>() {
  @Override public void handle(ActionEvent actionEvent) {
    // take some action
    ...
    // close the dialog.
    Node  source = (Node)  actionEvent.getSource(); 
    Stage stage  = (Stage) source.getScene().getWindow();
    stage.close();
  }
}
+21

JavaFX 2.1 . , jewelsea , ,

public class AboutBox extends Stage {

    public AboutBox() throws Exception {
        initModality(Modality.APPLICATION_MODAL);
        Button btn = new Button("Close");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                close();
            }
        });

        // Load content via
        // EITHER

        Parent root = FXMLLoader.load(getClass().getResource("AboutPage.fxml"));
        setScene(new Scene(VBoxBuilder.create().children(root, btn).build()));

        // OR

        Scene aboutScene = new Scene(VBoxBuilder.create().children(new Text("About me"), btn).alignment(Pos.CENTER).padding(new Insets(10)).build());
        setScene(aboutScene);

        // If your about page is not so complex. no need FXML so its Controller class too.
    }
}

,

new AboutBox().show();

.

+1

All Articles