【问题标题】:How to get selected value in observableArrayList type from ChoiceBox in JavaFX如何从 JavaFX 中的 ChoiceBox 中获取 observableArrayList 类型中的选定值
【发布时间】:2017-09-21 08:30:36
【问题描述】:

这个问题与 JavaFX 中关于 ChoiceBox 的其他问题类似,但我在代码中做了其他事情。 我有以下元素的类:

    package application;

public class ControllerRegister extends Main implements Initializable  {

@FXML
private ChoiceBox<String> cbSuppliers;
private ArrayList<String> suppliers = new ArrayList<String>();

public ControllerRegister() throws SQLException {/*....*/}

@FXML //controller method
void buttonOnAction2(ActionEvent event2) throws IOException, SQLException {
    //push some button and then get value of choicebox
    setStrTabDat() 
    /*....*/
}

public static void setStrTabDat(){ //my attempts to show selected value from ChoiceBox
    ObservableList<String> outputOl = FXCollections.observableArrayList();
     ChoiceBox<String> cbSuppliers = new ChoiceBox<String>();
     outputOl = cbSuppliers.getItems();
     outputOl.addAll(cbSuppliers.getValue());
     String output = cbSuppliers.getValue();
     System.out.println("output string: "+output);
     System.out.println("output by method: " +cbSuppliers.getItems());
     System.out.println("output observList: "+outputOl.toString());
}

@Override
public void initialize(URL arg0, ResourceBundle arg1) {
    ObservableList<String> list = FXCollections.observableArrayList(suppliers);
    cbSuppliers.setItems(list);
    cbSuppliers.getSelectionModel().selectFirst();
}
}

正如您在 setStrTabDat() 方法中看到的那样,我尝试从 ChoiceBox 打印选定的值,但所有三个 Sytem.out.prints 的输出都是“null”。我知道解决方案离我很近,所以请建议我该怎么做..

【问题讨论】:

    标签: java javafx combobox jcombobox observablelist


    【解决方案1】:

    也许你可以试试THIS LINK。他们在这里解释:

    • 如何创建 ChoiceBox();
    • 如何使用一个
    • 如何添加监听器
    • 如何检索数据

    基本上,它们会解释您需要了解的所有内容。

    祝你好运:)

    最好的问候, 迪米塔尔·格奥尔基耶夫

    【讨论】:

    • 谢谢,您的建议让我找到了解决方案;)
    【解决方案2】:

    正确的解决方案是在 initialize() 方法中添加 ChoiceBox 监听器,如下所示:

        @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        ObservableList<String> list = FXCollections.observableArrayList(suppliers);
        cbSuppliers.setItems(list);
        cbSuppliers.getSelectionModel().selectFirst();
        //and listener:
        cbSuppliers.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
        System.out.println(cbSuppliers.getItems().get((Integer) number2));
        }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多