0

我对 javaFX 中的组合框有一些问题。我在场景构建器中设计我的组合框:

<ComboBox fx:id="categoryComboBox" prefHeight="21.0" prefWidth="405.0" GridPane.columnIndex="1" GridPane.rowIndex="2">
      <items>
        <FXCollections fx:factory="observableArrayList">
          <String fx:value="Woodenware" />
          <String fx:value="Stoneware" />
          <String fx:value="Metalware" />
          <String fx:value="Fabric" />
        </FXCollections>
      </items>
    </ComboBox>

这是我的控制器类:

 @FXML
private ComboBox<?> categoryComboBox;
public void setCategoryComboBox(ComboBox<String> categoryComboBox) {
    this.categoryComboBox = categoryComboBox;
}

public ComboBox<String> getCategoryComboBox() {
    return categoryComboBox;
}

@FXML
private void comboBoxSelection(ActionEvent event) {
   categoryComboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
         public void changed(ObservableValue<? extends String> ov, 
             String old_val, String new_val) {
                String categoryStr =  getCategoryComboBox().getValue().toString(); //Don't know what to put here
     }

当我尝试从组合框中获取选定项目时:

  int category = panel.getCategoryComboBox().getValue()

它给了我一条错误消息“不兼容的数据类型,我不知道为什么。我是场景构建器和 netbeans 的新手,所以请告诉我我在哪里做错了。

提前致谢。

4

2 回答 2

0

Your ComboBox has a generic type specifier on it, so any value it returns will be a String.

You cannot assign a String to an int, which is why you get an "incompatible data type" error which you try to do so.

If instead, you set the category type to a String, you will no longer get an "incompatible data type error"

String category = panel.getCategoryComboBox().getValue()
于 2013-06-20T06:18:15.163 回答
0

错误在这一行:

private ComboBox<?> categoryComboBox;

你不能从?to投射int。所以将此行更改为:

private ComboBox<Integer> categoryComboBox;

然后你必须改变方法:

public ComboBox<String> getCategoryComboBox() {...}

 public ComboBox<Integer> getCategoryComboBox() {...}
于 2017-06-08T13:51:49.283 回答