replace JComboBox Contents - Java Swing

Java examples for Swing:JComboBox

Description

replace JComboBox Contents

Demo Code

// LICENSE:      This file is distributed under the BSD license.
//package com.java2s;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;

public class Main {
    public static void replaceComboContents(JComboBox cb, String[] items) {

        // remove listeners
        ActionListener[] listeners = cb.getActionListeners();
        for (int i = 0; i < listeners.length; i++)
            cb.removeActionListener(listeners[i]);

        if (cb.getItemCount() > 0)
            cb.removeAllItems();// w  ww .  ja v a2  s . c  o  m

        // add contents
        for (int i = 0; i < items.length; i++) {
            cb.addItem(items[i]);
        }

        // restore listeners
        for (int i = 0; i < listeners.length; i++)
            cb.addActionListener(listeners[i]);
    }
}

Related Tutorials