java-org.hwo.ui/src/org/hwo/models/ComboBoxHistoryModel.java

129 lines
2.5 KiB
Java

package org.hwo.models;
import java.util.Arrays;
import java.util.LinkedList;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
public class ComboBoxHistoryModel<E> implements ComboBoxModel<E> {
private LinkedList<ListDataListener> listDataListeners = new LinkedList<>();
private LinkedList<E> items = new LinkedList<>();
private E selectedItem;
private int historySize;
public ComboBoxHistoryModel()
{
this.selectedItem = null;
this.historySize = 10;
}
public ComboBoxHistoryModel(int historySize)
{
this.selectedItem = null;
this.historySize = historySize;
}
private void fireContentsChanged()
{
ListDataEvent lde = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, this.items.size());
for (ListDataListener l: listDataListeners) {
l.contentsChanged(lde);
}
}
@Override
public void addListDataListener(ListDataListener arg0) {
listDataListeners.add(arg0);
}
@Override
public E getElementAt(int arg0) {
return items.get(arg0);
}
@Override
public int getSize() {
return items.size();
}
@Override
public void removeListDataListener(ListDataListener arg0) {
listDataListeners.remove(arg0);
}
@Override
public Object getSelectedItem() {
return selectedItem;
}
@Override
public void setSelectedItem(Object arg0) {
selectedItem = (E)arg0;
if (items.contains(selectedItem)) {
items.remove(selectedItem);
}
items.add(0,selectedItem);
if (!clampHistory()) {
fireContentsChanged();
}
}
public int getHistorySize() {
return historySize;
}
public void setHistorySize(int historySize) {
this.historySize = historySize;
}
public Object[] getItems(){
return items.toArray();
}
public E[] getItems(E[] at) {
return items.toArray(at);
}
public void setItems(E[] items) {
this.items.clear();
this.items.addAll(Arrays.asList(items));
if (!this.items.contains(selectedItem)) {
selectedItem = null;
}
if (!clampHistory())
fireContentsChanged();
}
private boolean clampHistory() {
if (items.size() > historySize) {
while (items.size() > historySize) {
items.removeLast();
}
fireContentsChanged();
return true;
}
return false;
}
public void addElement(E element) {
this.items.add(0,element);
if (!clampHistory())
fireContentsChanged();
}
public void clear() {
items.clear();
fireContentsChanged();
}
public boolean contains(E val) {
return items.contains(val);
}
}