Javafx combobox not updating dropdown size upon change on realtime?

前端 未结 5 551
一整个雨季
一整个雨季 2021-02-09 13:00

I am using Javafx v8.0.25-b18.

The problem I occur is that the size of the dynamic combox\'s dropdown list doesn\'t change, so if I had initially two items in the dropdo

5条回答
  •  清歌不尽
    2021-02-09 13:42

    Just like to offer my two cents here. You may add the following codes to your combobox which define a custom listview popup that has variable height according to the current number of items. You can tweak the maximum number of items to be displayed in the popup.

    yourComboBox.setCellFactory(new Callback, ListCell>() {
            @Override
            public ListCell call(ListView param) {
                ListCell cell = new ListCell() {
                    @Override
                    public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        int numItems = getListView().getItems().size();
                        int height = 175;    // set the maximum height of the popup
                        if (numItems <= 5) height = numItems * 35;    // set the height of the popup if number of items is equal to or less than 5
                        getListView().setPrefHeight(height);
                        if (!empty) {
                            setText(item.toString());
                        } else {
                            setText(null);
                        }
                    }
                };
                return cell;
            }
        });
    

提交回复
热议问题