Nome do Evento

8 respostas
evertonsilvagomesjav

Tem algum evento que quando clicado na “setinha do comboBox” ele upa meu comboBox? Na inicializaçao do meu comboBox eu consigo preencher o model e o combo ja vir preenchido, porém queria que viesse vazio e quando clicado na seta ele upar o combo.

8 Respostas

ViniGodoy

O que você quer dizer com “upar” seu combo?

evertonsilvagomesjav

tenho um List quando clicar na seta do combo, preencher meu combo com essa Lista.

to fazendo assim:

ComboBoxModel comboModel = new DefaultComboBoxModel(list.toArray());

meuCombo.setModel(comboModel);

porem ja abre a janela com o combo "upado" ou "populado" ou " preenchido.

evertonsilvagomesjav

Outra coisa Vini tem outra forma de preencher o combo sem ser com DefaultCombo rsrs, sei que pra JTable tem e tem até um movimento seu rsrs.

ViniGodoy

Tem como você fazer o seu próprio Combobox model. Eu mesmo já sugeri um aqui no GUJ:

public class ArrayComboBoxModel<T> extends AbstractListModel implements
        MutableComboBoxModel
{
    private List<Object> list;
    private Object selectedObject;

    /**
     * Constructs an empty DefaultComboBoxModel object.
     */
    public ArrayComboBoxModel()
    {
        list = new ArrayList<Object>();
    }

    /**
     * Constructs a DefaultComboBoxModel object initialized with a collection.
     * 
     * @param v a Collection
     */
    public ArrayComboBoxModel(Collection< ? extends T> v)
    {
        list = new ArrayList<Object>();
        for (T obj : v)
            list.add(obj != null ? obj : "");

        if (size() > 0)
            selectedObject = get(0);
    }

    /**
     * Constructs a DefaultComboBoxModel object initialized with an array of
     * objects.
     * 
     * @param items an array of Object objects
     */
    public ArrayComboBoxModel(T... items)
    {
        this(Arrays.asList(items));
    }

    /**
     * Set the value of the selected item. The selected item may be null.
     * <p>
     * 
     * @param anObject The combo box value or null for no selection.
     * @throws ClassCastException If the object type is not T.
     */
    public void setSelectedItem(Object anObject)
    {
        if (anObject == null)
            anObject = "";

        selectedObject = anObject;
        fireContentsChanged(this, -1, -1);
    }

    @Deprecated
    public Object getSelectedItem()
    {
        return selectedObject;
    }

    @SuppressWarnings("unchecked")
    public T getSelected()
    {
        if ("".equals(selectedObject))
            return null;

        return (T) selectedObject;
    }

    /**
     * Deprecated, use size() instead.
     */
    @Deprecated
    public int getSize()
    {
        return size();
    }

    public int size()
    {
        return list.size();
    }

    /**
     * Deprecated, use get(int) instead.
     */
    @Deprecated
    public Object getElementAt(int index)
    {
        return list.get(index);
    }

    @SuppressWarnings("unchecked")
    public T get(int index)
    {
        if ("".equals(list.get(index)))
            return null;

        return (T) list.get(index);
    }

    /**
     * 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 indexOf(Object anObject)
    {
        if (anObject == null)
            anObject = "";

        return list.indexOf(anObject);
    }

    /**
     * Deprecated, use add(T) instead.
     */
    @SuppressWarnings("unchecked")
    @Deprecated
    public void addElement(Object anObject)
    {
        add((T) anObject);
    }

    public void add(T anObject)
    {
        Object object = anObject == null ? "" : anObject;

        list.add(object);
        fireIntervalAdded(this, list.size() - 1, list.size() - 1);

        if (list.size() == 1 && selectedObject == null && object != null)
            setSelectedItem(object);
    }

    public void addAll(Collection< ? extends T> elements)
    {
        addAll(elements, false);
    }

    public void addAll(Collection< ? extends T> elements, boolean sort)
    {
        if (elements.size() == 0)
            return;

        int first = list.size();
        for (T obj : elements)
            list.add(obj == null ? "" : obj);

        if (sort)
        {
            Collections.sort(list, new Comparator<Object>()
            {
                public int compare(Object o1, Object o2)
                {
                    return Collator.getInstance().compare(o1.toString(),
                            o2.toString());
                }
            });
        }

        fireIntervalAdded(this, first, list.size() - 1);
    }

    public void addAll(T... elements)
    {
        addAll(Arrays.asList(elements));
    }

    /**
     * Deprecated, use add(int, T) instead.
     */
    @SuppressWarnings("unchecked")
    @Deprecated
    public void insertElementAt(Object anObject, int index)
    {
        add(index, (T) anObject);
    }

    public void add(int index, T anObject)
    {
        Object obj = anObject == null ? "" : anObject;
        list.add(index, obj);
        fireIntervalAdded(this, index, index);
    }

    /**
     * Deprecated, use remove(int) instead.
     */
    @Deprecated
    public void removeElementAt(int index)
    {
        remove(index);
    }

    @SuppressWarnings("unchecked")
    public T remove(int index)
    {
        if (get(index) == selectedObject)
        {
            if (index == 0)
                setSelectedItem(size() == 1 ? null : get(index + 1));
            else
                setSelectedItem(get(index - 1));
        }

        Object removed = list.remove(index);
        if ("".equals(removed))
            removed = null;

        fireIntervalRemoved(this, index, index);

        return (T)removed;
    }

    /**
     * Deprecated, use remove(T) instead.
     */
    @SuppressWarnings("unchecked")
    @Deprecated
    public void removeElement(Object anObject)
    {
        remove((T) anObject);
    }

    public void remove(T anObject)
    {
        Object obj = anObject == null? "": anObject;
        int index = list.indexOf(obj);
        if (index != -1)
            remove(index);
    }

    public void clear()
    {
        if (list.size() == 0)
            return;

        int lastIndex = list.size() - 1;
        list.clear();
        fireIntervalRemoved(this, 0, lastIndex);
        selectedObject = null;
    }

    public boolean contains(T object)
    {
        return list.contains(object);
    }

    public boolean isEmpty()
    {
        return list.isEmpty();
    }

    public void fireIntervalRemoved(int index0, int index1)
    {
        super.fireIntervalRemoved(this, index0, index1);
    }

    public void fireContentsChanged(int index0, int index1)
    {
        super.fireContentsChanged(this, index0, index1);
    }

    public void fireIntervalAdded(int index0, int index1)
    {
        super.fireIntervalAdded(this, index0, index1);
    }

    public void removeAll(Collection<T> collection)
    {
        for (T item : collection)
            remove(item);
    }
}
evertonsilvagomesjav

:shock: tenho que ler com muiiiita calma pra entender rs.

ViniGodoy

Não me lembro ao certo, mas creio que o model só seja invocado quando a combo é clicada pela primeira vez. Talvez colocar uns breakpoints ajudem a resolver essa dúvida. Se for o caso, acho que implementar um mecanismo de lazy-loading no model seja mais do que suficiente.

ViniGodoy

A programação desse model é meio chata, mas o uso é bem trivial. Ele basicamente se comporta como um ArrayList. A única pentelhação é que você pode setar qualquer coisa no editor de textos do ComboBox, por isso tem vários métodos unchecked. Ele também suporta o campo vazio, pois muitas combos tem a opção de não escolher nenhum elemento.

Mas basicamente, ele tem uma série de métodos add, get, set e remove iguais ao do arrayList, que trabalham diretamente com a classe de negócios que está dentro do ComboBox, sem a necessidade de casts.

Para a maior parte das combos, funciona bem tranquilo.

evertonsilvagomesjav

poxa Vini bacana de mais muito obrigado, to lendo com calma, amanha vou fazer os testes com os breakpoints e vou debugar pra ver essa questão.

Criado 30 de março de 2010
Ultima resposta 30 de mar. de 2010
Respostas 8
Participantes 2