Java – JList items with icon

JavaIn this article I’ll present a code snippet how to implement a JList in Java where items will be displayed like [icon] [item text] .
Let’s have an example where list item contains simple text and a flag if the item is active or not. We will display green light If item is active and red light if it’s not active.

class ListItem {
  public boolean isActive;
  public String label;

  public ListItem(String label, boolean isActive) {
    this.label = label;
    this.isActive = isActive;
  }
}

Next we have a JFrame class which encapsulates our simple application

class MyApplication extends JFrame {
  private JList itemList;
 
  public MyApplication() {
    DefaultListModel listModel = new DefaultListModel();		
    
    itemList = new JList();
    itemList.setModel((ListModel) listModel);
    itemList.setCellRenderer(new IconLabelListRenderer());
    this.loadItemList();
  }

  private void loadItemList() {
    DefaultListModel listModel = (DefaultListModel)this.itemList.getModel();
    listModel.removeAllElements();

    for (int i = 1; i <= 5; i++) {
//    add five items where every second item will be set active (i%2==0)
      listModel.addElement(new ListItem("Item " + i, i%2 == 0));
  }
}

…and implement your custom list cell renderer:

public class IconLabelListRenderer extends DefaultListCellRenderer {
  private JLabel label;
  private final String RED_LIGHT = "/resources/icons/red_light.png";
  private final String GREEN_LIGHT = "/resources/icons/green_light.png";

  public IconLabelListRenderer(){
    label = new JLabel();
    label.setOpaque(true);
  }

  @Override
  public Component getListCellRendererComponent(
                     JList<? extends Object> list, 
                     Object value, 
                     int index, 
                     boolean selected, 
                     boolean expanded) {
    ListItem item = (ListItem)value;
		
    if(item.isActive) 
      this.label.setIcon(new ImageIcon(
        MyApplication.class.getResource(this.GREEN_LIGHT)
      ));
    else 
      this.label.setIcon(new ImageIcon(
        MyApplication.class.getResource(this.RED_LIGHT)
      ));
        
    this.label.setText(item.label);
    this.label.setToolTipText(item.label);
    if (selected) {
      label.setBackground(list.getSelectionBackground());
      label.setForeground(list.getSelectionForeground());
    } else {
      label.setBackground(list.getBackground());
      label.setForeground(list.getForeground());
    }

    return label;
  }
}

Leave a Reply