使用字符串列表作为组合框的源

时间:2010-02-21 08:44:20

标签: java swing combobox

我想使用String列表作为Java中jComboBox中各种选项的来源。你能说出使用哪种方法

谢谢

6 个答案:

答案 0 :(得分:6)

请参阅下面的答案...考虑到这是未经测试的,仅仅是一个例子。

你需要像Chandru那样创建ComboBoxModel的自定义实现, 然后使用setModel()方法在JComboBox上设置ComboBoxModel,并使用((CustomComboBoxModel<String>)jComboBox.getModel()).add(listOfThings);添加元素 像这样:

import java.util.List;
import javax.swing.ComboBoxModel;

/**
 * Custom Implementation of {@code ComboBoxModel} to allow adding a list of
 * elements to the list.
 */
public interface CustomComboBoxModel<T> extends ComboBoxModel {

    void add(List<T> elementsToAdd);

    List<T> getElements();

}

然后使用以下内容实现接口:

import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractListModel;

/**
 * Default Implementation of CustomComboBoxModel - untested.
 */
public class DefaultCustomComboBoxModel<T> extends AbstractListModel implements CustomComboBoxModel<T> {

    List<T> objects;
    T selectedObject;

    /**
     * Constructs an empty DefaultCustomComboBoxModel object.
     */
    public DefaultCustomComboBoxModel() {
        objects = new ArrayList<T>();
    }

    /**
     * Constructs a DefaultCustomComboBoxModel object initialized with
     * an array of objects.
     *
     * @param items  an array of Object objects
     */
    public DefaultCustomComboBoxModel(final T items[]) {
        objects = new ArrayList<T>();

        int i, c;
        for (i = 0, c = items.length; i < c; i++) {
            objects.add(items[i]);
        }

        if (getSize() > 0) {
            selectedObject = objects.get(0);
        }
    }

    // implements javax.swing.ComboBoxModel
    /**
     * Set the value of the selected item. The selected item may be null.
     * Make sure {@code anObject} is an instance of T otherwise a
     * ClassCastException will be thrown.
     * <p>
     * @param anObject The combo box value or null for no selection.
     */
    @Override
    public void setSelectedItem(Object anObject) {
        if ((selectedObject != null && !selectedObject.equals(anObject))
                || selectedObject == null && anObject != null) {
            selectedObject = (T) anObject;
            fireContentsChanged(this, -1, -1);
        }
    }

    // implements javax.swing.ComboBoxModel
    @Override
    public T getSelectedItem() {
        return selectedObject;
    }

    // implements javax.swing.ListModel
    @Override
    public int getSize() {
        return objects.size();
    }

    // implements javax.swing.ListModel
    @Override
    public T getElementAt(int index) {
        if (index >= 0 && index < objects.size()) {
            return objects.get(index);
        } else {
            return null;
        }
    }

    /**
     * Returns the index-position of the specified object in the list.
     *
     * @param anObject
     * @return an int representing the index position, where 0 is
     *         the first position
     */
    public int getIndexOf(T anObject) {
        return objects.indexOf(anObject);
    }

    // implements javax.swing.MutableComboBoxModel
    public void addElement(T anObject) {
        objects.add(anObject);
        fireIntervalAdded(this, objects.size() - 1, objects.size() - 1);
        if (objects.size() == 1 && selectedObject == null && anObject != null) {
            setSelectedItem(anObject);
        }
    }

    // implements javax.swing.MutableComboBoxModel
    public void insertElementAt(T anObject, int index) {
        objects.add(index, anObject);
        fireIntervalAdded(this, index, index);
    }

    // implements javax.swing.MutableComboBoxModel
    public void removeElementAt(int index) {
        if (getElementAt(index) == selectedObject) {
            if (index == 0) {
                setSelectedItem(getSize() == 1 ? null : getElementAt(index + 1));
            } else {
                setSelectedItem(getElementAt(index - 1));
            }
        }

        objects.remove(index);

        fireIntervalRemoved(this, index, index);
    }

    // implements javax.swing.MutableComboBoxModel
    public void removeElement(T anObject) {
        int index = objects.indexOf(anObject);
        if (index != -1) {
            removeElementAt(index);
        }
    }

    /**
     * Empties the list.
     */
    public void removeAllElements() {
        if (objects.size() > 0) {
            int firstIndex = 0;
            int lastIndex = objects.size() - 1;
            objects.clear();
            selectedObject = null;
            fireIntervalRemoved(this, firstIndex, lastIndex);
        } else {
            selectedObject = null;
        }
    }

    @Override
    public void add(List<T> elementsToAdd) {
        objects.addAll(elementsToAdd);
        fireContentsChanged(this, -1, -1);

    }

    @Override
    public List<T> getElements() {
        return objects;
    }
}

答案 1 :(得分:3)

扩展DefaultComboboxModel并创建一个方法,该方法接受Collection并设置该集合中的项目。使用setModel()将此自定义模型设置为组合框的模型。

答案 2 :(得分:1)

这里有代码从字符串数组创建组合框,您需要做的就是将列表转换为数组。     String petStrings = ...;

//Create the combo box, select item at index 4.
//Indices start at 0, so 4 specifies the pig.
JComboBox petList = new JComboBox(petStrings.toArray());

答案 3 :(得分:0)

最简单的方法是:

comboBox.setModel(new DefaultComboBoxModel(list.toArray()));

答案 4 :(得分:0)

我知道这是一篇旧帖子,但我想对edwardsmatt的DefaultCustomComboBoxModel做一点补充。不要忘记添加这个构造函数:

public DefaultCustomComboBoxModel(List<T> list) {
    objects = list;

    if (getSize() > 0) {
        selectedObject = objects.get(0);
    }
}

这样也可以用列表初始化模型,例如

myCombo.setModel(new DefaultCustomComboBoxModel(myList));

如果您使用((CustomComboBoxModel)myCombo.getModel()).add(myList),则需要明确设置所选项目。

答案 5 :(得分:0)

你也可以这样做:

 DefaultTableModel modelTabele = (DefaultTableModel) tblOsobe.getModel();
    modelTabele.addColumn("Ime");
    modelTabele.addColumn("Prezime");
    modelTabele.addColumn("Datum Rodjenja");

    for (Osoba osoba : Liste.osobe) {
        System.out.println("" + osoba);
        Object[] podaci = new Object[3];
        podaci[0] = osoba.getIme();
        podaci[1] = osoba.getPrezime();
        podaci[2] = osoba.getDatumRodjenja();
        modelTabele.addRow(podaci);

    }

此模型有3列,并且与Liste.osobe字符串列表中的行数一样多。