1

我正在使用场景构建器,我想出了 3 个选择框。第二个选择框取决于第一个选择框的输入,第三个取决于第二个。我怎样才能做到这一点?

我试过这个

@FXML
private ChoiceBox  course;

course.getSelectionModel().selectedIndexProperty().addListener(
        (ObservableValue<? extends Number> ov,
             Number old_val, Number new_val) -> { 
                //some code here
            }
    );

但是这个事件只有在我切换值时才会发生,第一次选择不会触发这个事件,这不是我想要的。我怎样才能做到这一点,在此先感谢。

4

1 回答 1

0

你可以做这样的事情,每次完成一个动作,它都会设置下一个动作的值。请注意,.getItems().clear();这将确保列表每次都被清空,这样您就不会在列表中包含旧值。然而,for 循环并不重要,只是为了给我添加的文本值添加一些变化

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        ChoiceBox<String> choiceBoxOne = new ChoiceBox<>();
        choiceBoxOne.setPrefWidth(100);
        choiceBoxOne.getItems().addAll("Choice1", "Choice2", "Choice3");

        ChoiceBox<String> choiceBoxTwo = new ChoiceBox<>();
        choiceBoxTwo.setPrefWidth(100);

        ChoiceBox<String> choiceBoxThree = new ChoiceBox<>();
        choiceBoxThree.setPrefWidth(100);

        choiceBoxOne.setOnAction(event -> {
            choiceBoxTwo.getItems().clear();
            //The above line is important otherwise everytime there is an action it will just keep adding more
            if(choiceBoxOne.getValue()!=null) {//This cannot be null but I added because idk what yours will look like
                for (int i = 3; i < 6; i++) {
                    choiceBoxTwo.getItems().add(choiceBoxOne.getValue() + i);
                }
            }
        });

        choiceBoxTwo.setOnAction(event -> {
            choiceBoxThree.getItems().clear();
            //The above line is important otherwise everytime there is an action it will just keep adding more
            if(choiceBoxTwo.getValue()!=null) {//This can be null if ChoiceBoxOne is changed
                for (int i = 6; i < 9; i++) {
                    choiceBoxThree.getItems().add(choiceBoxTwo.getValue() + i);
                }
            }
        });


        VBox vBox = new VBox();
        vBox.setPrefSize(300, 300);
        vBox.setAlignment(Pos.TOP_CENTER);
        vBox.getChildren().addAll(choiceBoxOne, choiceBoxTwo, choiceBoxThree);

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

    public static void main(String[] args) { launch(args); }
}
于 2019-05-10T13:00:35.390 回答