I'm using Netbeans to develop my Java application.I want to display list of items with icons. I have use ListCellRenderer but it just display item, but not icon. Here is my code
//Item class
public class Item {
private String title;
private String imagePath;
private ImageIcon image;
//getter and setter}
//ItemRenderer
public class ItemRenderer extends JLabel implements ListCellRenderer{
private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
public ItemRenderer() {
setOpaque(true);
setIconTextGap(12);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{ try
{
Item item = (Item)value;
System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhh" + item.getTitle() + ";icon=" + item.getImagePath());
setText(item.getTitle());
setIcon(item.getImage());
if (isSelected)
{
setBackground(HIGHLIGHT_COLOR);
setForeground(Color.white);
}
else
{
setBackground(Color.white);
setForeground(Color.black);
}
}
catch(UnsupportedOperationException ex)
{
throw new UnsupportedOperationException("Not supported yet.");
}
return this;
}
//and here is my code to use ListCellRenderer
public frmMain() {
initComponents();
DefaultListModel model = new DefaultListModel();
Item [] items = null;
items = new Item[5];
for(int i=0;i<5;i++)
{
items[i] = new Item();
items[i].setTitle("Item " + i);
items[i].setImagePath("pdf-gif.gif");
model.addElement(items[i]);
}
lstLeftItems.setModel(model);
lstLeftItems.setCellRenderer(new ItemRenderer());
lstLeftItems.setVisibleRowCount(5);
}
Notes: lstLeftItems is a Jlist.
Pls help me to fix this bug.