Scene Builder,如何配对ComboBoxs选择

时间:2016-01-10 22:40:06

标签: java javafx combobox scenebuilder

使用jdk1.7.0_80.jdk: 我有2个ComboBoxes;我想从mainComboBox中选择一个值,并根据从mainComboBox中选择的值自动加载subCombobox。并且在subComboBox中有其独特的选择集:我的初始化工作如下面的屏幕截图所示。 enter image description here

现在我的问题是当我更改mainComboBox的值时。当我这样做时,在subComoboBox中没有预先选择/显示任何内容。我使用comboBoxChoice加载ObservableList中可用的不同选项。但由于一些奇怪的原因,它没有踢。

enter image description here

public class FXMLDocumentController implements Initializable {
    ObservableList<String> mainList = FXCollections.observableArrayList("Main-1","Main-2","Main-3");
     ObservableList<String> main1SubList = FXCollections.observableArrayList("Main1-Sub1","Main1-Sub2","Main1-Sub3");
     ObservableList<String> main2SubList = FXCollections.observableArrayList("Main2-Sub1","Main2-Sub2","Main2-Sub3");
     ObservableList<String> main3SubList = FXCollections.observableArrayList("Main3-Sub1","Main3-Sub2","Main3-Sub3");


    @FXML
    private ComboBox mainComboBox, subComboBox;


   @Override 
    public void initialize(URL url, ResourceBundle rb) {
        mainComboBox.setValue("Main-1");
        mainComboBox.setItems(mainList);

        subComboBox.setValue("Main1-Sub1");
       subComboBox.setItems(main1SubList);
     }    

    @FXML
    private void comboBoxChoice() {
        if (mainComboBox.getValue().equals("Main-1") ) {
            subComboBox.setValue("Main1-Sub1");
            subComboBox.setItems(main1SubList);
        }
        if (mainComboBox.getValue().equals("Main-2") ) {
            subComboBox.setValue("Main2-Sub1");
            subComboBox.setItems(main2SubList);
        }
        if (mainComboBox.getValue().equals("Main-3") ) {
            subComboBox.setValue("Main3-Sub1");
            subComboBox.setItems(main3SubList);
        }

    }
}

FXML文件:

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafxapplication18.FXMLDocumentController">
    <children>
        <Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
      <ComboBox fx:id="mainComboBox" layoutX="103.0" layoutY="136.0" onAction="#comboBoxChoice" prefWidth="150.0" />
      <ComboBox fx:id="subComboBox" layoutX="103.0" layoutY="162.0" prefWidth="150.0" />
    </children>
</AnchorPane>

1 个答案:

答案 0 :(得分:1)

这对我来说在JDK 1.8.0_66上运行正常。可能是这是一个已经修复过的旧bug。

我建议改变setValue()@FXML private void comboBoxChoice() { if (mainComboBox.getValue().equals("Main-1") ) { subComboBox.setItems(main1SubList); subComboBox.setValue("Main1-Sub1"); } if (mainComboBox.getValue().equals("Main-2") ) { subComboBox.setItems(main2SubList); subComboBox.setValue("Main2-Sub1"); } if (mainComboBox.getValue().equals("Main-3") ) { subComboBox.setItems(main3SubList); subComboBox.setValue("Main3-Sub1"); } } 的顺序;替换所有项目可能会删除旧的选定项目,即使它位于“新”列表中。

.attr(...)