Peter Penzov
Peter Penzov

Reputation: 1728

Implementing Toggle Full Screen menu item

I created this code basing on JavaFX tutorial:

    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);

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

EDIT: This code works but the implementation is very ugly.

Upvotes: 0

Views: 224

Answers (1)

Sergey Grinev
Sergey Grinev

Reputation: 34528

  1. Check real status rather then text
  2. Use binding to update text and you will not need to care about initialization and fullscreen mode changed by other methods

    MenuItem fullScreen = new MenuItem();
    
    fullScreen.textProperty().bind(
         new When(primaryStage.fullScreenProperty())
              .then("Exit Full Screen")
              .otherwise("Full Screen"));
    
    fullScreen.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            primaryStage.setFullScreen(!primaryStage.isFullScreen());
        }
    });
    

Upvotes: 3

Related Questions