【问题标题】:JavaFX removing performed action if checkbox is unselected如果未选中复选框,JavaFX 将删除已执行的操作
【发布时间】:2019-02-11 02:29:31
【问题描述】:

我是 JavaFX 的初学者。在我的程序中,当一个复选框被选中时,我希望它显示一个标签和一个选择框。但是,当它未被选中时,我希望这两个都消失。但是,我不太确定如何执行此操作。

这是我的代码:

String [] options = new String [] {"A", "B", "C", "D", "E", "F"};
CheckBox [] cbs = new CheckBox[options.length];

    for (int i = 0; i < options.length; i++){
        final CheckBox cb = cbs[i] = new CheckBox(options[i]);
        cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                if(observable.getValue() == true){
                    ChoiceBox<Integer> choice = new ChoiceBox<>();
                    Label label = new Label("How many of the selected accounts do you have?");
                    choice.getItems().addAll(1, 2, 3, 4, 5);
                    choice.setValue(1);
                    selection.setAlignment(Pos.BOTTOM_LEFT);
                    selection.getChildren().addAll(label, choice);
                    gp.add(selection, 0, 8);
                } else if (observable.getValue() == false){
                    // remove above block if getValue() == false;
                }
            }
       });
   }

【问题讨论】:

    标签: java javafx checkbox


    【解决方案1】:

    您需要保留对节点的引用。您可以通过向匿名 ChangeListener 添加字段或向循环主体添加(有效的)最终局部变量来做到这一点。

    我不确定selection 是什么,但对多个复选框使用同一个节点似乎是个坏主意。

    以下示例只是添加/删除包含LabelChoiceBoxVBox。由于这会改变布局,我建议改为禁用节点或更改可见性而不是添加/删除节点。

    @Override
    public void start(Stage primaryStage) throws Exception {
        String[] options = new String[]{"A", "B", "C", "D", "E", "F"};
        GridPane grid = new GridPane();
    
        for (int i = 0; i < options.length; i++) {
            final int row = i;
            String option = options[i];
            CheckBox checkBox = new CheckBox(option);
    
            ChoiceBox<Integer> choice = new ChoiceBox<>();
            Label label = new Label("How many of the selected accounts do you have?");
            choice.getItems().addAll(1, 2, 3, 4, 5);
    
            VBox choiceContainer = new VBox(label, choice);
    
            checkBox.selectedProperty().addListener((o, oldValue, newValue) -> {
                if (newValue) {
                    grid.add(choiceContainer, 1, row);
                } else {
                    grid.getChildren().remove(choiceContainer);
                }
            });
    
            grid.add(checkBox, 0, row);
        }
    
        Scene scene = new Scene(grid);
    
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多