Here you can find the source of addFirstItem(JComboBox
Parameter | Description |
---|---|
T | the element type |
combobox | the combobox |
item | the item |
public static <T> void addFirstItem(JComboBox<T> combobox, T item)
//package com.java2s; /*/*from w w w . j av a 2s . 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. */ 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); } } }