JavaFX 设置数组中的标签文本

JavaFX setting Label text from an Array

我正在尝试使用 JavaFX 进行多项选择测验。我会有一个用于显示问题的标签,一个用于保存问题的字符串数组和一个用于显示可能答案的 ToggleGroups 数组。

如果用户按下 "Next" 按钮,标签应更改其文本并显示字符串数组中的下一个元素,可能答案的文本也应相应更改,但是,我不能让它甚至对 Label 也起作用。

我当前的代码只是遍历数组并且只显示最后一个元素一次,但我需要它从第一个问题开始并在每次用户按下 "Next" 时显示下一个问题。任何帮助将不胜感激。

这只是我尝试做的一个例子:

public class setLay extends Application{

String[]text = new String[4];

Label label = new Label();

Button next = new Button("Next");
@Override

public void start(Stage primaryStage) throws Exception {

    text[0]= "What's the capital of Monaco?";
    text[1] = "What's the capital of San Marino?";
    text[2] = "What's the capital of Lithuania?";
    text[3] = "What's the capital of Denmark?";

    label.setText(text[0]);
    label.setTranslateX(200);

    next.setOnAction(e -> makeLabel());

    Stage stage = new Stage();
    Pane pane = new Pane();
    Scene scene = new Scene(pane, 800, 500);
    stage.setScene(scene);
    stage.show();

    pane.getChildren().addAll(label, next);

    }

public void makeLabel() {

    for(int i=0; i<text.length; i++) {

        label.setText(text[i]);

          }

       }



    }

只需将当前问题存储在一个实例变量中,并在每次单击按钮时递增它:

public class setLay extends Application{

    private int currentQuestionIndex = 0 ;

    String[]text = new String[4];

    Label label = new Label();

    Button next = new Button("Next");
    @Override

    public void start(Stage primaryStage) throws Exception {

        text[0]= "What's the capital of Monaco?";
        text[1] = "What's the capital of San Marino?";
        text[2] = "What's the capital of Lithuania?";
        text[3] = "What's the capital of Denmark?";

        label.setText(text[0]);
        label.setTranslateX(200);

        next.setOnAction(e -> makeLabel());

        Stage stage = new Stage();
        Pane pane = new Pane();
        Scene scene = new Scene(pane, 800, 500);
        stage.setScene(scene);
        stage.show();

        pane.getChildren().addAll(label, next);

    }

    public void makeLabel() {
        currentQuestionIndex = (currentQuestionIndex + 1) % text.length ;
        label.setText(text[currentQuestionIndex]);
    }
}

如果你使用 IntegerProperty 而不是普通的 int,你可以做各种有趣的事情:

private IntegerProperty currentQuestionIndex = new SimpleIntegerProperty();

// ...

// label.setText(text[0]);
label.textProperty().bind(Bindings.createStringBinding(() -> 
    text[currentQuestionIndex.get()], currentQuestionIndex);

next.disableProperty().bind(currentQuestionIndex.isEqualTo(text.length -1 ));

// next.setOnAction(e -> makeLabel());
next.setOnAction(e -> currentQuestionIndex.set(currentQuestionIndex.get()+1));