Menu items to enter and exit full-screen mode in JavaFX

Posted on

Problem

I need to improve this by using switch statement in which I want to set the text and setFullScreen. Is there any more elegant way to implement this?

final String change[] =
    {
        "Full Screen", "Exit Full Screen"
    };
    final MenuItem fullScreen = MenuItemBuilder.create().text(change[0]).build();

    fullScreen.setOnAction(new EventHandler<ActionEvent>()
    {
        @Override
        public void handle(ActionEvent e)
        {
            fullScreen.setText((fullScreen.getText().equals(change[0])) ? change[1] : change[0]);

            if (fullScreen.getText().equals(change[0]))
            {

                primaryStage.setFullScreen(false);
            }
            else
            {

                primaryStage.setFullScreen(true);
            }

        }
    });

    view.getItems().add(fullScreen);

Solution

This can be made a lot more elegant with the State Pattern.

We’ll introduce an enum for the two states :

private static enum Mode {
    FULLSCREEN("Exit Full Screen"), NORMAL("Full Screen");

    private final String toggleActionText;

    private Mode(String text) {
        this.toggleActionText = text;
    }

    public String getToggleActionText() {
        return toggleActionText;
    }

    public boolean isFullScreen() {
        return FULLSCREEN == this;
    }

    public Mode other() {
        return isFullScreen() ? NORMAL : FULLSCREEN;
    }
}

Then, having added a properly initialized Mode field to the class, you can simplify your code to this :

final MenuItem fullScreen = MenuItemBuilder.create().text(mode.getToggleActionText()).build();

fullScreen.setOnAction(new EventHandler<ActionEvent>()
{
    @Override
    public void handle(ActionEvent e)
    {
        mode = mode.other();
        fullScreen.setText(mode.getToggleActionText());
        primaryStage.setFullScreen(mode.isFullScreen());
    }
});

view.getItems().add(fullScreen);

As you can see, it is a lot simpler to delegate the state dependent behavior to the Mode instance than to use an if whenever you have state dependent behavior.

Leave a Reply

Your email address will not be published. Required fields are marked *