4
\$\begingroup\$

Write a program to display the text Welcome to Java and LearningJavaFX alternately with a mouse click.

package com.example.demo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class MouseEventDemo extends Application {
    boolean displayFirstText = false;

    @Override
    public void start(Stage primaryStage) {
        Pane pane = new Pane();
        Text text1 = new Text(20, 20, "Learning JavaFX");
        Text text2 = new Text(30, 30, "Welcome to Java");
        pane.addEventHandler(MouseEvent.MOUSE_CLICKED, e -> {

            if (!displayFirstText) {
                pane.getChildren().clear();
                pane.getChildren().add(text2);
                displayFirstText = true;
            } else {
                pane.getChildren().clear();
                pane.getChildren().add(text1);
                displayFirstText = false;
            }
        });
        Scene scene = new Scene(pane, 300, 100);
        primaryStage.setTitle("MouseEventDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

I am concerned with that if/else statement part. It seems like it could be made more readable. I'd love a cleaner way to toggle the variable, and I appreciate further improvements as well.

\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

In addition to coderodde's suggestion, you can apply DRY by moving the repeated pane.getChildren().clear() before the if statement (as it happens regardless of the condition tested):

pane.getChildren().clear();
if (!displayFirstText) {
    pane.getChildren().add(text2);
    // ...
} else {
    pane.getChildren().add(text1);
    // ...
}

You could also simplify the if statement by using the conditional operator ?::

pane.getChildren().clear();
pane.getChildren().add(displayFirstText ? text1 : text2);
\$\endgroup\$
5
\$\begingroup\$

You could simply do:

b = !b;

for a boolean b.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.