javafx fxml 组合框错误

javafx fxml ComboBox Error

我正在尝试将字符串添加到 javafx 组合框,但我不断收到上述错误:/

no suitable method found for add(String)
method Collection.add(CAP#1) is not applicable
  (argument mismatch; String cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
  (argument mismatch; String cannot be converted to CAP#1)
   where CAP#1 is a fresh type-variable:
  CAP#1 extends Object from capture of ?

代码

room_id.getItems().add("Hello");

FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>


<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.AutoMaven.ui.controller.ComboTestController">
   <children>
      <ComboBox fx:id="room_id" layoutX="170.0" layoutY="185.0" prefHeight="31.0" prefWidth="260.0" />
   </children>
</AnchorPane>

更新

使用列表后,我得到

不兼容的类型:字符串无法转换为 CAP#1
其中 CAP#1 是一个新的类型变量:
CAP#1 从 ?

的捕获扩展对象
ObservableList<String> list=FXCollections.observableArrayList("1","2","3","4");

room_id.setItems(list);

这是因为未设置 ComboBox 元素类型,因此默认为“?”。 像这样:

ComboBox<?> room_id = new ComboBox<>(); 

所以要强制 fxml ComboBox 具有字符串值,您必须添加如下内容:

<ComboBox fx:id="cbo_Bacteriologie_Aesculine" prefHeight="21.0" prefWidth="105.0" GridPane.columnIndex="1" GridPane.rowIndex="0">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="string option" />
        </FXCollections>
    </items>
</ComboBox>

或通过如下代码设置可观察列表:

Java ComboBox .setItems (ObservableList < T > value)

只需将控制器 class 中的 room_id 字段声明为

@FXML
private ComboBox<String> room_id;

如果您正在使用

@FXML
private ComboBox<?> room_id;

room_id.getItems() returns a ObservableList<?> 即具有未知元素类型的 ObservableList 并且 String 无法分配给此类型。