Search code examples
javajavafxbooleanalerttetris

JavaFX EventHandler - new Alert if boolean equals true


When the user has reached the end of this Tetris game I want a new alert to be opened.

In the model class I have a boolean that will switch to true if a new Tetris block cannot be spawned.

I'm working with model view presenter, so in the model is the boolean + getter and in the presenter a new alert will be created if the boolean returns true.

The question is how do I add this to the eventHandlers() in the presenter?

public Presenter(Model model, View view) {
this.model = model;
this.view = view;
addEventHandlers();
}

private void addEventHandlers() {
//view.setOnKeyPressed... this is for rotating the blocks to give you an example
}

Solution

  • JavaFX implements observable properties, which are extensions of the Java Bean pattern that support notification for invalidation and for changes to the underlying value. These are fundamental to the JavaFX library: all controls in JavaFX make use of these. So, for example, if you want to respond to changes to the text in a text field, you would do

    myTextField.textProperty().addListener((observable, oldText, newText) -> {
        // ... do something with newText (and perhaps oldText) here...
    });
    

    So you can just achieve this with a BooleanProperty (or similar) in your model class:

    private final BooleanProperty gameEnded = new SimpleBooleanProperty();
    
    public BooleanProperty gameEndedProperty() {
        return gameEnded ;
    }
    
    public final boolean isGameEnded() {
        return gameEndedProperty().get();
    }
    
    public final void setGameEnded(boolean gameEnded) {
        gameEndedProperty().set(gameEnded);
    }
    

    Then you can do:

    model.gameEndedProperty().addListener((obs, gameWasEnded, gameIsNowEnded) -> {
        if (gameIsNowEnded) {
            // show alert, etc...
        }
    });
    

    See "Properties and Bindings" in the Oracle tutorial for more details, including bindings, etc. You might also consider a ReadOnlyBooleanWrapper if you don't want the property to be changed from outside the class it is defined in.