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 rela开发者_运维技巧tively light, so I'd prefer to not use a component that's part of a monolithic widget library, and open source is preferred.
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);
}
}
}
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..
精彩评论