views:

48

answers:

2

I am looking for code that will add favorites / MRU type behavior to a JComboBox.

I could code this myself, but it sure seems like someone else has probably already done it.

I found the following (which looks exactly like what I want, but the source code is nowhere near complete): http://java.sys-con.com/node/36658

Any suggestions? I need to keep this relatively light, so I'd prefer to not use a component that's part of a monolithic widget library, and open source is preferred.

A: 

What about just subclassing JComboBox and overriding the

public void addItem(Object anObject)

to give it the functionality you want?

You can just keep an internal list of items synched with the effective one, and whenever you add a new item it can check if size() >= maxItems and trim down least recent ones.

Then you should find a way to refresh an item whenever it is used. If its selection it's enough to be refreshed you can write an ItemListener that does it. Otherwise you'll need a specified external action or an observer/observable pattern..

Jack
+1  A: 

Consider extending DefaultComboBoxModel: override addElement() and insertElementAt() to insert at zero and remove the last element.

Addendum: Here's an example; per SO, the license is cc-wiki. I'd use Preferences to persist the entries.

class MRUComboBoxModel extends DefaultComboBoxModel {

    @Override
    public void addElement(Object element) {
        this.insertElementAt(element, 0);
    }

    @Override
    public void insertElementAt(Object element, int index) {
        super.insertElementAt(element, 0);
        int size = this.getSize();
        if (size > 10) {
            this.removeElementAt(size - 1);
        }
    }
}
trashgod
That'll do for my needs (deciding when to add elements will require a focus change listener, which is easy enough). The component described in the link in the question is a lot fancier, but your approach is sufficient for what I'm doing. Thanks.
Kevin Day