Java examples for Swing:JComboBox
Checks if the item is in the combobox.
/*/*from w w w . ja v a2 s .c o m*/ * Copyright 2008-2014, David Karnok * The file is part of the Open Imperium Galactica project. * * The code should be distributed under the LGPL license. * See http://www.gnu.org/licenses/lgpl.html for details. */ //package com.java2s; import java.util.Objects; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; public class Main { /** * Checks if the item is in the combobox. If yes, then it is moved to the beginning, * otherwise, the item is added as first. * @param <T> the element type * @param combobox the combobox * @param item the item */ public static <T> void addFirstItem(JComboBox<T> combobox, T item) { int idx = -1; DefaultComboBoxModel<T> model = (DefaultComboBoxModel<T>) combobox .getModel(); for (int i = 0; i < model.getSize(); i++) { T t = model.getElementAt(i); if (Objects.equals(t, item)) { idx = i; break; } } model.insertElementAt(item, 0); if (idx >= 0) { model.removeElementAt(idx + 1); } } }