I'm a beginner with JavaFx and I'm experiencing a problem with simply closing a stage. Basically I'm trying to do create a class that's a confirmation box controller. There's a 'yes' button and and a 'no' button, but either way the stage should close and continue with the application:
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
// more imports...
public class ConfirmBoxController implements IView {
public javafx.scene.control.Button BTN_save;
public javafx.scene.control.Label label_Message;
private Stage stage;
private boolean answer;
private String title;
private String message;
public ConfirmBoxController(){
this("Confirmation","Are you sure?");
}
public ConfirmBoxController(String title, String message){
this.title = title;
this.message = message;
stage = new Stage();
}
public boolean confirm(){
try{
stage = new Stage();
FXMLLoader fxmlLoader = new FXMLLoader();
Parent root = fxmlLoader.load(getClass().getResource("ConfirmBox.fxml").openStream());
Scene scene = new Scene(root, 250, 140);
stage.setTitle(title);
stage.setScene(scene);
stage.showAndWait();
return answer;
}
catch(Exception E){
E.printStackTrace();
return true;
}
}
public void yes(ActionEvent actionEvent) {
answer = true;
stage.close();
}
public void no(ActionEvent actionEvent) {
answer = false;
stage.close();
}
Note: IView is an empty interface. Basically the stage comes up, I can click the buttons and I know that this is being registered since the functions "yes" and "no" print when I click the buttons. But nothing happens.
I'm sure I'm overseeing something basic, but I haven't found how to do this properly. Thank you.
give your button a name in the controller class: @FXML public Button closeButton;
and add like 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" />