如何恰当的让文字的文字和颜色在4种颜色之间达到toggle/change?

How to appropriately get the text and color of the text to toggle/change between 4 colors?

我目前将我的 JavaFX 代码设置为在蓝色和红色之间切换。当程序运行时,带有文本 "Change to Red" 的按钮以蓝色文本显示。如果我单击该按钮,它会变为 "Change to Blue" 红色文本。如果我再次单击它,循环将重新开始。我想做的是应用相同的图案,但使用四种颜色。例如,我希望它以:

开头

"Change to Red",用蓝色文字书写。

然后点击后

"Change to Green",用红色文字书写。

然后点击后

"Change to Purple",绿色文字。

然后点击后

"Change to Blue",紫色文字。

然后在点击后重新开始循环:

"Change to Red",用蓝色文字书写。

等等等

这是我有两种颜色的代码:

public class FirstUserInput extends Application {

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Change to Red");
        btn.setTextFill(Color.BLUE);

    btn.setOnAction(e -> {
        if (btn.getTextFill() == Color.RED) {
            btn.setText("Change to Red");
            btn.setTextFill(Color.BLUE);
        } else {
            btn.setText("Change to Blue");
            btn.setTextFill(Color.RED);
        }
    });

任何人都可以帮我更改此代码以使用四种颜色吗?

好吧,如果您想减少必须使用 if-else 语句编写的代码,那么可以使用数组或枚举来保存所有选项,并在每个动作事件上选择正确的选项,例如:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class TestApp extends Application {

    private int index = 0;

    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Change to Red");

        String allTexts[] = { "Change to Red", "Change to Blue", "Change to Green", "Change to Pink" };
        Color allColors[] = { Color.BLUE, Color.RED, Color.PINK, Color.GREEN };

        btn.setOnAction(e -> {

            index++;
            if(index >= allTexts.length ) {
                index = 0;
            }

            btn.setText(allTexts[index]);
            btn.setTextFill(allColors[index]);

        });

        VBox box = new VBox();
        box.getChildren().add(btn);

        primaryStage.setScene(new Scene(box));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

以上内容在顺序更改时有效我希望你正在寻找什么。