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.