views:

35

answers:

2

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.

+1  A: 

Based on the code you provide, the Icon is null. I see where you set the title and imagePath, but nowhere to you actually read the image file to create the icon.

If you need more help post your SSCCE so we can see the real problem.

camickr
Hooray for SSCCE! \o/
Bombe
A: 

Hi! Thanks for your answer. I did not set image beacause of my getter method for Image attribute Here is my code

 public ImageIcon getImage() {

    if(image==null)
    {
        image = new ImageIcon(imagePath);
    }
    return image;
}

So, just set imagePath is enough.

Chan Tee Pye