Javafx combobox with custom object displays object address though custom cell factory is used

后端 未结 2 1239
遇见更好的自我
遇见更好的自我 2020-12-09 08:52

I have a combobox which shows list of User objects. I have coded a custom cell factory for the combobox:

@FXML ComboBox cmbUserIds;
         


        
相关标签:
2条回答
  • 2020-12-09 09:43

    You need to provide a functional fromString() Method within the Converter!

    I had the same problem as you have and as I implemented the fromString() with working code, the ComboBox behaves as expected.

    This class provides a few of my objects, for dev-test purposes:

    public class DevCatProvider {
    
        public static final CategoryObject c1;
        public static final CategoryObject c2;
        public static final CategoryObject c3;
    
        static {
            // Init objects
        }
    
        public static CategoryObject getCatForName(final String name) {
            switch (name) {
                case "Kategorie 1":
                    return c1;
    
                case "Cat 2":
                    return c2;
    
                case "Steuer":
                    return c3;
    
                default:
                    return c1;
            }
        }
    }
    

    The converter object:

    public class CategoryChooserConverter<T> extends StringConverter<CategoryObject> {
    
        @Override
        public CategoryObject fromString(final String catName) {
            //This is the important code!
            return Dev_CatProvider.getCatForName(catName);
        }
    
        @Override
        public String toString(final CategoryObject categoryObject) {
            if (categoryObject == null) {
                return null;
            }
            return categoryObject.getName();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 09:58

    Just create and set a CallBack like follows:

    @FXML ComboBox<User> cmbUserIds;
    
    Callback<ListView<User>, ListCell<User>> cellFactory = new Callback<ListView<User>, ListCell<User>>() {
    
        @Override
        public ListCell<User> call(ListView<User> l) {
            return new ListCell<User>() {
    
                @Override
                protected void updateItem(User item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item == null || empty) {
                        setGraphic(null);
                    } else {
                        setText(item.getId() + "    " + item.getName());
                    }
                }
            } ;
        }
    }
    
    // Just set the button cell here:
    cmbUserIds.setButtonCell(cellFactory.call(null));
    cmbUserIds.setCellFactory(cellFactory);
    
    0 讨论(0)
提交回复
热议问题