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
