How to close a java window with a button click - JavaFX Project

后端 未结 6 1854
忘掉有多难
忘掉有多难 2020-12-05 18:26

I made a JavaFX project and created the GUI for the first-login frame in the java Scene Builder. When the login is successful, the login frame must be closed and the next fr

相关标签:
6条回答
  • 2020-12-05 19:00

    Thanks for your time to reply,but in the end I found out how to fix it. I used

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

    in the if that it's responsible for the successful login. I mean, after a dialog appears that informs the user about their successful login, that code goes there.

    (I imported the right stuff too in order to make that line of code work)

    0 讨论(0)
  • 2020-12-05 19:01

    Use

    stage.hide()
    

    If you do this from a controller, you can get the stage from any Node inside the scene of the stage (if necessary let the FXML loader assign one to a field of the controller using the id attribute from the fxml namespace in the fxml):

    Window stage = node.getScene().getWindow();
    
    0 讨论(0)
  • 2020-12-05 19:01

    Although

        getScene().getWindow();
    

    on a Node will get you the stage from the controller, it's important to note that calling close() or hide() are equivalent, and will simply make the login window invisible. As for using dispose():

    This link might help to clear up any confusion.

    0 讨论(0)
  • 2020-12-05 19:05

    give your button a name in the controller class:

    @FXML
    public Button closeButton;
    

    and add this method:

    @FXML
    public void handleCloseButtonAction(ActionEvent event) {
        Stage stage = (Stage) closeButton.getScene().getWindow();
        stage.close();
    }
    

    In your FXML you need a reference to the button name and the method to call onAction:

    <Button fx:id="closeButton" cancelButton="true" layoutX="350.0" layoutY="767.0" mnemonicParsing="false" onAction="#handleCloseButtonAction" prefWidth="100.0" text="Close" />
    

    This would close the stage that this button is on.

    0 讨论(0)
  • 2020-12-05 19:07

    Hide doesn't close the window, just put in visible mode. The best solution was:

    @FXML
    private void exitButtonOnAction(ActionEvent event){
            ((Stage)(((Button)event.getSource()).getScene().getWindow())).close();      
    }
    
    0 讨论(0)
  • 2020-12-05 19:10

    Similar to the other answers but more precise.

    @FXML
    public void handleCloseButtonAction(ActionEvent event) {
        ((Stage)(((Button)event.getSource()).getScene().getWindow())).close();
    }
    
    0 讨论(0)
提交回复
热议问题