javafx fxml ComboBox Error

一个人想着一个人 提交于 2019-12-01 07:44:11

问题


Im trying to add a String to a javafx comboBox but i keep getting the above error :/

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 ?

CODE

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>

UPDATE

After using a list, i get

incompatible types: String cannot be converted to CAP#1
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?

ObservableList<String> list=FXCollections.observableArrayList("1","2","3","4");

room_id.setItems(list);

回答1:


Simply declare the room_id field in your controller class as

@FXML
private ComboBox<String> room_id;

If you're using

@FXML
private ComboBox<?> room_id;

room_id.getItems() returns a ObservableList<?> i.e. a ObservableList with unknown element type and String cannot be assigned to this type.




回答2:


this is because the ComboBox elements type is not set so it's by defauld "?". like this :

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

so to force the fxml ComboBox to have String values you have to add something like this :

<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>

or set the observable list from code like this :

Java ComboBox .setItems (ObservableList < T > value)



来源:https://stackoverflow.com/questions/48042708/javafx-fxml-combobox-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!