我正在尝试使用JavaFX进行多项选择测验。我会有一个用于显示问题的标签,一个用于保存问题的字符串数组和一个用于显示可能答案的ToggleGroups数组。
如果用户按下“下一步”按钮,Label应该更改其文本并显示字符串数组中的下一个元素,也可能相应地更改可能答案的文本,但是,我无法使其工作甚至是标签。
我刚刚遍历数组的当前代码只显示最后一个元素,但我需要从第一个问题开始,每次用户按“下一步”时显示下一个问题。任何帮助将不胜感激。
这只是我想要做的一个例子:
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]);
}
}
}
答案 0 :(得分:1)
只需将当前问题存储在实例变量中,然后在每次单击按钮时将其递增:
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));