Imagem nos itens do JComboBox [RESOLVIDO]

3 respostas
A

Bom dia pessoal,

estou com um problema, gostaria de colocar imagens nos itens de um jcombobox para o meu projeto…
Ex: ao abrir uma combobox aparecer a imagem e ao lado sua descrição…

Sei que para isso tenho que implementar um ListCellRenderer … bom entao vou postar o código que fiz.

Tenho essas variáveis declaradas:

private List<FormaPagamento> listaFormaPagamento;  
    private ImageIcon[] imagens;  
    private String[] textos;

Essa parte está no construtor do formulário:

listaFormaPagamento = new ColFormaPagamento(conexao).consultar(); //aqui pego todas as formas de pagamento cadastradas no banco de dados  
            textos = new String[listaFormaPagamento.size()];  
            for (int i = 0; i < listaFormaPagamento.size(); i++){  
                textos[i] = listaFormaPagamento.get(i).getDescricao();  
                System.out.println("Textos["+i+"]: "+textos[i]);  
            }  
      
            imagens = new ImageIcon[textos.length];  
            Integer[] intArray = new Integer[textos.length];  
            for (int i = 0; i < textos.length; i++) {  
                intArray[i] = new Integer(i);  
                if (listaFormaPagamento.get(i).getIcone() != null)  
                    imagens[i] = new ImageIcon(listaFormaPagamento.get(i).getIcone());  
                else  
                    imagens[i] = new ImageIcon(getClass().getResource("/cpadivisual/imagem/sem_imagem.jpg"));  
      
                imagens[i].setDescription(textos[i]);  
            }  
       
            cbFormaPagamento = new JComboBox(intArray);  
            ComboBoxRenderer renderer = new ComboBoxRenderer();  
            renderer.setPreferredSize(new Dimension(200, 130));  
            cbFormaPagamento.setRenderer(renderer);  
            cbFormaPagamento.setMaximumRowCount(3);

E tenho essa classe que implementa do ListCellRenderer:
Classe baseada no linkhttp://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/CustomComboBoxDemoProject/src/components/CustomComboBoxDemo.java

class ComboBoxRenderer extends JLabel implements ListCellRenderer {  
              
            private Font uhOhFont;  
      
            public ComboBoxRenderer() {  
                setOpaque(true);  
                setHorizontalAlignment(CENTER);  
                setVerticalAlignment(CENTER);  
            }  
      
             
            public Component getListCellRendererComponent(  
                                               JList list,  
                                               Object value,  
                                               int index,  
                                               boolean isSelected,  
                                               boolean cellHasFocus) {  
      
                int selectedIndex = ((Integer)value).intValue();  
      
                if (isSelected) {  
                    setBackground(list.getSelectionBackground());  
                    setForeground(list.getSelectionForeground());  
                } else {  
                    setBackground(list.getBackground());  
                    setForeground(list.getForeground());  
                }  
      
                ImageIcon icon = imagens[selectedIndex];  
                String formaPagamento = textos[selectedIndex];  
                setIcon(icon);  
                if (icon != null) {  
                    setText(formaPagamento);  
                    setFont(list.getFont());  
                } else {  
                    setUhOhText(formaPagamento + "(Sem Imagem)", list.getFont());  
                }  
      
                return this;  
            }  
      
            protected void setUhOhText(String uhOhText, Font normalFont) {  
                if (uhOhFont == null) {   
                    uhOhFont = normalFont.deriveFont(Font.ITALIC);  
                }  
                setFont(uhOhFont);  
                setText(uhOhText);  
            }  
        }

O problema é que não aparece nada no meu combobox … ao abrir ele não aparece nenhum item … ou seja … fica em branco…

Como eu posso fazer para adicionar os itens que estou carregando nos arrays texto e imagens???

Desde já agradeço a ajuda
Alan

3 Respostas

D

Talvez isto ajude

A

Olá drsmachado,

obrigado por responder!!

então segundo o post que vc enviou eu fiz o seguinte código no construtor da classe:

listaFormaPagamento = new ColFormaPagamento(conexao).consultar();
        Object[] itens = new Object[listaFormaPagamento.size()];
        ImageIcon img;
        for (int i = 0; i < listaFormaPagamento.size(); i++){
            if (listaFormaPagamento.get(i).getIcone() != null)
                img = new ImageIcon(listaFormaPagamento.get(i).getIcone());
            else
                img = new ImageIcon(getClass().getResource("/cpadivisual/imagem/sem_imagem.jpg"));
            img.setDescription(listaFormaPagamento.get(i).getDescricao());
            itens[i] = img;
        }
        cbFormaPagamento = new JComboBox(itens);

porém este codigo apresentou o mesmo resultado do outro, ou seja, aparece o combobox em branco … sem nenhum item…
o que posso estar fazendo errado?

algumas considerações:
estou usando o netbeans 7.0.1
esta variável “listaFormaPagamento.get(i).getIcone()” me retorna um array de bytes.

novamente agradeço

A

Consegui resolver pessoal,

obrigado ao amigo dsrmachado e aos que tentaram ajudar de alguma forma

segue o código e a imagem de como ficou para quem passar pelo mesmo problema

Código no construtor da classe:

listaFormaPagamento = new ColFormaPagamento(conexao).consultar();
        ImageIcon img;
        for (int i = 0; i < listaFormaPagamento.size(); i++){
            if (listaFormaPagamento.get(i).getIcone() != null)
                img = new ImageIcon(listaFormaPagamento.get(i).getIcone());
            else
                img = new ImageIcon(getClass().getResource("/cpadivisual/imagem/sem_imagem.jpg"));
            img.setDescription(listaFormaPagamento.get(i).getDescricao());
            cbFormaPagamento.addItem(img);
        }
        
        ComboBoxRenderer renderer = new ComboBoxRenderer();
        cbFormaPagamento.setRenderer(renderer);
        cbFormaPagamento.setMaximumRowCount(3);

Código do ListCellRenderer:

class ComboBoxRenderer extends JLabel implements ListCellRenderer {
        public ComboBoxRenderer() {
            setOpaque(true);
            setHorizontalAlignment(LEADING);
            setVerticalAlignment(CENTER);
        }
        public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus)
        {
            if (isSelected) {
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }

            ImageIcon icon = (ImageIcon)value;
            //nesta linha é possível redimensionar a imagem para o tamanho desejado Ex: 60 largura, 40 altura
            Image img = icon.getImage().getScaledInstance(60, 40, Image.SCALE_DEFAULT);
            setText(icon.getDescription());
            setIcon(new ImageIcon(img));
            return this;
        }
    }

imagem do resultado:

Abraço!!

Criado 17 de agosto de 2012
Ultima resposta 17 de ago. de 2012
Respostas 3
Participantes 2