javaswingjcombobox

JComboBox change displayed text every time any change is made


I am trying to edit the displayed text (in the JComboBox itself, not the dropdown popup of options) every single time that any option is clicked/changed.

I have a custom renderer that looks kind of like the one below:

JComboBox<Object> jc = new JComboBox<Object>();
jc.setRenderer(new ListCellRenderer<Object>() {
    @Override
    public Component getListCellRendererComponent(JList<? extends Item> list,
                                                  Object value, int index, 
                                                  boolean isSelected,
                                                  boolean cellHasFocus) {
        if(index == -1)
            return new JLabel("this is the top cell");

        return new JLabel("this is a cell in the dropdown popup area");
    }
});

This successfully changes the text whenever the renderer is called. The trouble is that this renderer is not called every time an entry is clicked.

I have tried to make a custom event call in my class that extends JComboBox, but when trying to call a change, I'm not sure how to specify that I only want to change the top text (and leave the rest of the dropdown cells alone). I have been messing with the method:

fireItemStateChanged(new ItemEvent(this,ItemEvent.ITEM_STATE_CHANGED,
                                               somethingGoesHere,
                                               ItemEvent.DESELECTED));

but I can't figure out what item Object to put in place of somethingGoesHere to specify to call for a re-render to the top text. None of the entries in dataModule.getElementAt(int index) seem to create a call to change the correct text.

(My extending class of JComboBox has made large-ish changes including making the dropdown popup not automatically hide when an option is clicked, which is probably why the top text doesn't change as often as expected and I am trying to call the renderer on my own.)

EDIT:

After a bit of testing, the problem is that I want the JComboBox display bit to refresh even if the dropdown item that was previously selected is clicked again.

I tried overriding setSelectedItem(Object anObject) to call selectedItemChanged() even when selectedItemReminder == dataModule.getSelectedItem(), but this doesn't then force an update of the JComboBox display text. :(


Solution

  • I think I figured it out!

    The event I needed to explicitly call was fireContentsChanged(this, -1, -1) within the DefaultComboBoxModel, so I extended that class into a custom model so my extension of JComboBox could tell the model to run that method. This successfully forces the ListCellRenderer to update the display text I'm trying to change.

    The DefaultComboBoxModel usually is the one that calls for updates to the display text of the JComboBox from the model's setSelectedItem(Object anObject) method.