user3758262
user3758262

Reputation: 21

JComboBox list based model

In my program I use couple JComboBoxes with a simple list combo box model:

public class ListComboBoxModel<T> extends AbstractListModel implements ComboBoxModel {
    protected List<T> list;
    private T selection;

    public ListComboBoxModel(List<T> list) {
        this.list = list;
        this.selection = getDefaultSelection();
    }

    protected T getDefaultSelection() {
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public Object getSelectedItem() {
        return selection;
    }

    @Override
    public void setSelectedItem(Object anItem) {
        selection = (T) anItem;
    }

    @Override
    public int getSize() {
        return list.size();
    }

    @Override
    public T getElementAt(int index) {
        return list.get(index);
    }
}

And the problem is that when I add elements to the list that combobox is using it doesn't work as intended anymore. If I click on combo box, the list has correct length but all elements in there are empty so the list is all white. When I roll over an element it doesn't highlight. When I click anywhere in the list it always works as if I selected the recently added element. If I reduce list size back to original or even decrease it, combo box works as it should have. To edit the lists that combo boxes use, I use JTables and the add method I implemented in their models.

public void add(T element) {
    list.add(element);
    fireTableDataChanged();
}

Any ideas how can I fix that?

Upvotes: 0

Views: 61

Answers (1)

user3758262
user3758262

Reputation: 21

Well if anyone were interested I solved problem by adding

fireContentsChanged(this, 0, getSize());

in a method that gets called when by table/list gets changed anywhere in the program using observer pattern.

Upvotes: 1

Related Questions