All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.brunothg.swing2.model.SortedComboBoxModel Maven / Gradle / Ivy

package com.github.brunothg.swing2.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.SortOrder;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

import com.github.brunothg.swing2.utils.DefaultComparator;
import com.github.brunothg.swing2.utils.Null;

public class SortedComboBoxModel extends DefaultComboBoxModel implements
		ListDataListener {

	private static final long serialVersionUID = 1L;

	private SortOrder sortOrder;
	private Comparator comparator;

	private boolean sorting = false;

	public SortedComboBoxModel(SortOrder sortOrder, Comparator comparator) {

		this.sortOrder = Null.nvl(sortOrder, SortOrder.UNSORTED);
		this.comparator = Null.nvl(comparator, new DefaultComparator());

		addListDataListener(this);
	}

	@Override
	public void intervalAdded(ListDataEvent e) {

		if (sortOrder != SortOrder.UNSORTED) {

			sort();
		}
	}

	@Override
	public void intervalRemoved(ListDataEvent e) {
	}

	@Override
	public void contentsChanged(ListDataEvent e) {

		if (sortOrder != SortOrder.UNSORTED) {

			sort();
		}
	}

	private void sort() {

		if (sorting || sortOrder == SortOrder.UNSORTED) {
			return;
		}

		Object selectedItem = getSelectedItem();
		sorting = true;

		List elements = new ArrayList(getSize());

		for (int i = 0; i < getSize(); i++) {

			elements.add(getElementAt(i));
		}

		Collections.sort(elements, comparator);

		if (sortOrder == SortOrder.ASCENDING) {
			Collections.reverse(elements);
		}

		removeAllElements();

		for (E element : elements) {

			insertElementAt(element, 0);
		}

		setSelectedItem(selectedItem);
		sorting = false;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy