Java - icono en JList

 
Vista:

icono en JList

Publicado por dani (55 intervenciones) el 09/03/2006 16:15:59
Buenas, nunca he usado un Jlist y no tengo ni idea de como añadirle un icono a cada item de la lista.

Alguno sabeis comom puedo hacerlo?
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:icono en JList

Publicado por Jonathan (30 intervenciones) el 10/03/2006 01:21:24
Saludos, en la api del JList hay un ejemplo de como colocarle iconos y texto al JList, es sencillo, solo tienes que hacer una clase que implemente ListCellRenderer. El siguiente ejemplo lo tome de la api, te lo voy a comentar un poco:

Haz una clase que implemente ListCellRenderer:

class MyCellRenderer extends JLabel implements ListCellRenderer {

final static ImageIcon longIcon = new ImageIcon("icono.gif"); // el icono

// el unico metodo definido por ListCellRenderer es este:

public Component getListCellRendererComponent(
JList list,
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // the list and the cell have the focus
{
String s = value.toString();
setText(s);
setIcon(longIcon);

if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
return this;
}
}

luego desde donde tengas el JList aplicale el metodo setCellRenderer:
ejemplo:

String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
dataList.setCellRenderer(new MyCellRenderer());

Y Listo ya lo tienes. NOTA EL EJEMPLO LO TOME DE LAS API, SOLO LO MODIFIQUE UN POCO.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar