Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

close fxml window by code, javafx

I need to close the current fxml window by code in the controller

I know stage.close() or stage.hide() do this in fx

how to implement this in fxml? I tried

private void on_btnClose_clicked(ActionEvent actionEvent) {         Parent root = FXMLLoader.load(getClass().getResource("currentWindow.fxml"));             Scene scene = new Scene(root);          Stage stage = new Stage();                     stage.setScene(scene);         stage.show(); } 

but it doesn't work!

All help will be greatly appreciated. Thanks!

like image 443
alfredo138923 Avatar asked Nov 26 '12 14:11

alfredo138923


People also ask

How do I close FXML?

@ZinMinn if you want to close the app, just call Platform. exit(). Closing a stage is different than closing the app (you can have multiple stages). This solution is perfect to close a secondary window.

How do you exit a scene in JavaFX?

Be default, to quit the program is to let the user click the standard window close button, typically represented by an X in the upper-right corner of the window's title bar.

What does platform exit do?

It's generally recommended that you exit a JavaFX Application with a call to Platform. exit() , which allows for a graceful shutdown: for example if there is any "cleanup" code you need, you can put it in the stop() method and Platform. exit() will allow it to be executed.


2 Answers

  1. give your close button an fx:id, if you haven't yet: <Button fx:id="closeButton" onAction="#closeButtonAction">
  2. In your controller class:

    @FXML private javafx.scene.control.Button closeButton;  @FXML private void closeButtonAction(){     // get a handle to the stage     Stage stage = (Stage) closeButton.getScene().getWindow();     // do what you have to do     stage.close(); } 
like image 55
a.b Avatar answered Sep 29 '22 00:09

a.b


If you have a window which extends javafx.application.Application; you can use the following method. (This will close the whole application, not just the window. I misinterpreted the OP, thanks to the commenters for pointing it out).

Platform.exit(); 

Example:

public class MainGUI extends Application { .........  Button exitButton = new Button("Exit"); exitButton.setOnAction(new ExitButtonListener()); .........  public class ExitButtonListener implements EventHandler<ActionEvent> {    @Override   public void handle(ActionEvent arg0) {     Platform.exit();   } } 

Edit for the beauty of Java 8:

 public class MainGUI extends Application {     .........      Button exitButton = new Button("Exit");     exitButton.setOnAction(actionEvent -> Platform.exit());  } 
like image 27
codepleb Avatar answered Sep 29 '22 00:09

codepleb