Replace the options in a combo box with a new set. - Java Swing

Java examples for Swing:JComboBox

Description

Replace the options in a combo box with a new set.

Demo Code


//package com.java2s;

import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;

public class Main {
    /**/*from   w ww.  j a  va2 s.com*/
     * Replace the options in a combo box with a new set.
     * nulls are skipped.  Selected value is preserved.
     *
     * @param combob GUI component to update
     * @param values list of values to put into component, or null to erase
     */
    public static void replaceContents(JComboBox combob, Object[] values) {
        Object cur = combob.getSelectedItem();
        DefaultComboBoxModel m = (DefaultComboBoxModel) combob.getModel();
        m.removeAllElements();
        if (values != null)
            for (Object v : values)
                if (v != null)
                    m.addElement(v);
        combob.setSelectedItem(cur);
        combob.setEnabled(true);
    }

    /**
     * Replace the options in a combo box with a new set.
     * nulls are skipped.  Selected value is preserved.
     *
     * @param combob GUI component to update
     * @param values list of values to put into component, or null to erase
     */
    public static void replaceContents(JComboBox combob, Vector<?> values) {
        Object cur = combob.getSelectedItem();
        DefaultComboBoxModel m = (DefaultComboBoxModel) combob.getModel();
        m.removeAllElements();
        if (values != null)
            for (Object v : values)
                if (v != null)
                    m.addElement(v);
        combob.setSelectedItem(cur);
        combob.setEnabled(true);
    }

    /**
     * Replace the options in a combo box with a new set.
     * nulls are skipped.  Selected value is preserved.
     *
     * @param combob GUI component to update
     * @param values list of values to put into component, or null to erase
     */
    public static void replaceContents(JComboBox combob, List<?> values) {
        Object cur = combob.getSelectedItem();
        DefaultComboBoxModel m = (DefaultComboBoxModel) combob.getModel();
        m.removeAllElements();
        if (values != null)
            for (Object v : values)
                if (v != null)
                    m.addElement(v);
        combob.setSelectedItem(cur);
        combob.setEnabled(true);
    }
}

Related Tutorials