Search code examples
javaandroidjavafxcomboboxobservablelist

Android adapter alternative in Java FX


I've already seached Google but didn't find any useful information.
I am using Adapter for combobox to select name and get it's id. (not position index, id come from databse) in Android. But I don't know how to use it in JavaFx?

I have tried JavaFx POJO in a list that came from from the database id and name.
I add to ObservableList and setItems(list.getName()) to Combobox.
When Combobox selected get it's position index and use this index and get real id from list. list.getID(index)

Is this the best/correct way? Or is there an Android Adapter alternative for Java FX?


Solution

  • You would show items that contain both name and id in the ComboBox and specify how the items are converted to Strings that are shown in the ComboBox.

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

    Of course you could also use a different kind of items, if that's more convenient for you. E.g. Integer(= indices in list) could be used and the StringConverter could be used to convert the index to a name from the list (and id) or you could use the ids as items of the ComboBox and use a Map to get the strings associated with the ids in the StringConverter.

    If you want to add more flexibility in how your items are represented visually, you could use a cellFactory instead to create custom ListCells (there is an example in the javadoc linked). If you use this together with a ComboBox of Integers 0, 1, ..., itemcount-1 you could get pretty close to a android Adapter. However using a StringConverter seems to be sufficient in this case.