by Dinesh Thakur

JListThe JList is a list on which we can view and select more than one item simultaneously. In case there are more items than can be simultaneously displayed due to the size of the list, a vertical scroll bar appears. Relevant methods:

 

public JList () Creates an empty JList;
public JList (Object [] listaItems) created with the items contained in the array of objects;
public JList (Vector listaItems) created with the Vector elements;
getSelectedIndex public int (): returns the index of the first selected item (-1 if none);
public int [] getSelectedIndices (): returns an array of indices that are selected;
getSelectedValue public Object () gives the reference to the object;
public Object [] getSelectedValues ​​(): returns an array of Object
selected.

 

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JavaExampleListImageInJApplet extends JApplet
{
    public void init()
    {
        Container Cntnr = getContentPane();
        newModel NwModl = new newModel();
        newRenderer NwRndrer = new newRenderer();
        JList Lst = new JList(NwModl);
        Lst.setCellRenderer(NwRndrer);
        Lst.setVisibleRowCount(5);
        Cntnr.add(new JScrollPane(Lst));
    }
}
      class newModel extends DefaultListModel
       {
           public newModel()
           {
               for(int loop_indx = 0; loop_indx <= 10; loop_indx++)
                    {
                       addElement(new Object[] {"ITEM :" + loop_indx,new ImageIcon("Koala.jpg")});
                    }
           }
       }
             class newRenderer extends JLabel implements ListCellRenderer
               {
                  public newRenderer()
                    {
                       setOpaque(true);
                    }
                       public Component getListCellRendererComponent(JList JLst, Object ob1, int indx, boolean isSelected,boolean Focus)
                         {
                             newModel Mdl = (newModel)JLst.getModel();
                             setText((String)((Object[])ob1)[0]);
                             setIcon((Icon)((Object[])ob1)[1]);
                             if(!isSelected)
                          {
                                 setBackground(JLst.getBackground());
                                setForeground(JLst.getForeground());
                              }
                                else
                            {
                                        setBackground(JLst.getSelectionBackground());
                                        setForeground(JLst.getSelectionForeground());
                                    }
                                        return this;
                          }
                }
/*<APPLET CODE=JavaExampleListImageInJApplet.class WIDTH=310 HEIGHT=310 ></APPLET>*/

Java - Add an image to a JList item