JComboBox que exibe imagens - Problemas

1 resposta
J

Olá pessoal…

Eu estou desenvolvendo um sistema de descrição visual de objetos através de ícones…Pensei em oferecer os ícones em JComboBoxes. Para isto implementei um ListCellRenderer específico que, em tese, deveria exibir essas imagens…Segue o código abaixo:

class OntologyValueRender extends JLabel implements ListCellRenderer
{
    private List<OntologyDefinedValueStringAndIcon> items;

    public OntologyValueRender(List<OntologyDefinedValueStringAndIcon> items)
    {
        this.items = items;
        setOpaque(true);
        setHorizontalAlignment(CENTER);
        setVerticalAlignment(CENTER);
    }

    /*
     * This method finds the image and text corresponding
     * to the selected value and returns the label, set up
     * to display the text and image.
     */
    public Component getListCellRendererComponent(
                                       JList list,
                                       Object value,
                                       int index,
                                       boolean isSelected,
                                       boolean cellHasFocus) {
        //Get the selected index. (The index param isn't
        //always valid, so just use the value.)
        //int selectedIndex = ((Integer)value).intValue();
        int selectedIndex = index;

        if (isSelected) {
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else {
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }

        if(index>=0 && index<this.items.size())
        {
            System.out.println("índice: "+index);
            //Set the icon and text.  If icon was null, say so.
            if (this.items.get(selectedIndex).getIcon() == null)
            {
                if(this.items.get(selectedIndex).getOntologyDefinedValueString()!=null)
                {
                    this.setText(this.items.get(selectedIndex).getOntologyDefinedValueString().getValue());
                    //System.out.println("ontologia nulo!");
                }
                else
                {
                    this.setText("");
                }
            }
            else
            {
                ImageIcon icon = new ImageIcon(this.items.get(selectedIndex).getIcon());
                this.setIcon(icon);
                this.setToolTipText(this.items.get(selectedIndex).getOntologyDefinedValueString().getValue());
            }
        }
        else
        {
            this.setText("");
        }

        return this;
    }
}

Este renderer recebe no construtor uma lista de objetos OntologyDefinedValueStringAndIcon, que encapsulam uma representação textual e uma representação pictórica para uma determinada característica visual.

Os Combobox até estão exibindo os ícones como esperado. No entanto, quando eu seleicono um deles, na caixa fica selecionado outro…Queria saber se alguém já teve este tipo de problema.

1 Resposta

J

Desculpa aí pessoal…Eu já descobri as besterias que havia feito :oops:

Segue o novo código corrigido:

class OntologyValueRender extends JLabel implements ListCellRenderer
{
    public OntologyValueRender()
    {
        setOpaque(true);
        setHorizontalAlignment(CENTER);
        setVerticalAlignment(CENTER);
    }

    /*
     * This method finds the image and text corresponding
     * to the selected value and returns the label, set up
     * to display the text and image.
     */

    public Component getListCellRendererComponent(
                                       JList list,
                                       Object value,
                                       int index,
                                       boolean isSelected,
                                       boolean cellHasFocus) {
        //Get the selected index. (The index param isn't
        //always valid, so just use the value.)
        //int selectedIndex = ((Integer)value).intValue();
        int selectedIndex = index;

        if (isSelected) {
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else {
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }

        if(value!=null)
        {
            OntologyDefinedValueStringAndIcon objeto = (OntologyDefinedValueStringAndIcon)value;
            if (objeto.getIcon() == null)
            {
                if(objeto.getOntologyDefinedValueString()!=null)
                {
                    this.setText(objeto.getOntologyDefinedValueString().getValue());
                    //System.out.println("ontologia nulo!");
                }
                else
                {
                    this.setText("");
                }
            }
            else
            {
                ImageIcon icon = new ImageIcon(objeto.getIcon());
                this.setIcon(icon);
                this.setToolTipText(objeto.getOntologyDefinedValueString().getValue());
            }
        }
        else
        {
            this.setText("");
        }

        return this;
    }

}

No código anterior eu recebia como parâmetro a mesma lista de elementos que o Model mantinha…não me dei conta de que no método getListCellRendererComponent eu recebo o valor (value)…Aí deixei a classe para cuidar só da representação, com base apenas nos parãmetros recebidos neste método…

Agora está funcionando direitinho…

Criado 8 de junho de 2010
Ultima resposta 8 de jun. de 2010
Respostas 1
Participantes 1