Java JComboBox Item addFirstItem(JComboBox combobox, T item)

Here you can find the source of addFirstItem(JComboBox combobox, T item)

Description

Checks if the item is in the combobox.

License

LGPL

Parameter

Parameter Description
T the element type
combobox the combobox
item the item

Declaration

public static <T> void addFirstItem(JComboBox<T> combobox, T item) 

Method Source Code

//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);
        }
    }
}

Related

  1. addHeadersaveFileTypeItemsTo(JComboBox combo)
  2. addItems(JComboBox comboBox, Iterable items)
  3. contains(final JComboBox comboBox, final Object item)
  4. fillCombo(JComboBox comboBox, Collection items)