2015-11-12 44 views
1

我已經找到Google,但沒有找到任何有用的信息。
我使用Adapter作爲組合框來選擇名稱並得到它的ID。 (不是位置索引,id來自databse)。但我不知道如何在JavaFx中使用它?Java FX中的Android適配器替代

我已經在從數據庫ID來到清單試過了JavaFx POJO
我將ObservableListsetItems(list.getName())添加到Combobox中。
當Combobox選擇獲取它的位置索引並使用此索引並從列表中獲得真實ID。 list.getID(index)

這是最好的/正確的方式?或者Java FX有沒有Android Adapter替代品?

回答

1

您將顯示包含在ComboBoxnameid並指定項目如何轉換爲那些在ComboBox所示String的項目進行。

ComboBox<Item> comboBox = new ComboBox<>(); 

comboBox.setItems(FXCollections.observableArrayList(new Item("foo", "17"), new Item("bar", "9"))); 
comboBox.setConverter(new StringConverter<Item>() { 

    @Override 
    public Item fromString(String string) { 
     // converts string the item, if comboBox is editable 
     return comboBox.getItems().stream().filter((item) -> Objects.equals(string, item.getName())).findFirst().orElse(null); 
    } 

    @Override 
    public String toString(Item object) { 
     // convert items to string shown in the comboBox 
     return object == null ? null : object.getName(); 
    } 
}); 

// Add listener that prints id of selected items to System.out   
comboBox.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends Item> observable, Item oldValue, Item newValue) -> { 
    System.out.println(newValue == null ? "no item selected" : "id=" + newValue.getId()); 
}); 
class Item { 
    private final String name; 
    private final String id; 

    public String getName() { 
     return name; 
    } 

    public String getId() { 
     return id; 
    } 

    public Item(String name, String id) { 
     this.name = name; 
     this.id = id; 
    } 

} 

當然你也可以使用不同類型的項目,如果這是對你更方便。例如。可以使用Integer(=列表中的索引)並且可以使用StringConverter將索引轉換爲列表(和id)中的名稱,或者可以使用ID作爲ComboBox的項目並使用Map來獲取關聯的字符串在StringConverter的ID。

如果您想增加更多的靈活性以直觀地表示項目,則可以使用cellFactory來代替創建自定義ListCell(在鏈接的javadoc中有一個示例)。如果你使用ComboBoxInteger s 0, 1, ..., itemcount-1,你可能會非常接近android Adapter。然而在這種情況下使用StringConverter似乎就足夠了。