【问题标题】:Linking combobox in JavaFx在 JavaFx 中链接组合框
【发布时间】:2020-07-16 04:22:29
【问题描述】:

我有一个带有三个组合框的界面。每个组合框显示对象的一个​​属性,并根据大小写按字母顺序或数字顺序排序。当我从组合框中选择一个项目(属性)时,其他两个应选择与对象对应的项目(属性)。

我找不到有关它的文档,也不知道如何做。我只找到有关嵌套组合框的信息,但事实并非如此。

希望你能理解。

【问题讨论】:

标签: javafx combobox binding fxml


【解决方案1】:

在此示例中,我向其中一个组合框添加了一个侦听器,该侦听器“侦听”组合框选定值的更改。在该组合框中选择一个值后,第二个组合框会自行调整以具有相应的值。您可以通过向每个组合框添加侦听器来采用相同的逻辑并以 3 种方式应用它。如果您有任何问题,请告诉我!

ComboBox<String> combo = new ComboBox<String>();
combo.getItems().add("1");
combo.getItems().add("2");
combo.getItems().add("3");
combo.getSelectionModel().select(0); // value index to select

ComboBox<String> combo2 = new ComboBox<String>();
combo2.getItems().add("10");
combo2.getItems().add("20");
combo2.getItems().add("30");
combo2.getSelectionModel().select(0);

combo.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue ov, String oldVal, String newVal) {
        if (newVal.equals("1"))
            if (combo2.getSelectionModel().getSelectedIndex() != 0)
                combo2.getSelectionModel().select(0);
        if (newVal.equals("2"))
            if (combo2.getSelectionModel().getSelectedIndex() != 1)
            combo2.getSelectionModel().select(1);
        if (newVal.equals("3"))
            if (combo2.getSelectionModel().getSelectedIndex() != 2)
            combo2.getSelectionModel().select(2);
    }
});

【讨论】:

  • 是的,我理解其中的逻辑,但是,如果 combo2 而不是数字,它有单词,例如:按字母顺序排列的“十”、“二十”、“三十”。如果它有数百个项目怎么办。
  • 您可以使用我上面提供的信息轻松实现这一目标。 combo2.getSelectionmodel().select(combo.getSelectionModel.getSelectedIndex())
猜你喜欢
  • 1970-01-01
  • 2017-01-07
  • 2012-06-16
  • 1970-01-01
  • 2013-06-16
  • 2023-03-29
  • 2019-08-23
  • 2017-02-08
相关资源
最近更新 更多