How do add a checkbox to items in a JList?


import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;

public class CheckListExample
{
   public static void main(String args[])
   {
      JFrame Jframe = new JFrame();
      Jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      // Create a list containing CheckBoxItem's

      JList jlist = new JList(new CheckBoxItem[] {
            new CheckBoxItem("apple"),
            new CheckBoxItem("orange"),
            new CheckBoxItem("mango"),
            new CheckBoxItem("paw paw"),
            new CheckBoxItem("banana")});

      
      // to renderer list cells

      jlist.setCellRenderer(new CheckListRendererItm());
      jlist.setSelectionMode(
         ListSelectionModel.SINGLE_SELECTION);

      // Add a mouse listener to handle changing selection

      jlist.addMouseListener(new MouseAdapter()
      {
         public void mouseClicked(MouseEvent event)
         {
            JList jlist = (JList) event.getSource();

            // Get index of item clicked

            int index = jlist.locationToIndex(event.getPoint());
            CheckBoxItem Citem = (CheckBoxItem)
               jlist.getModel().getElementAt(index);

            // Toggle selected state

            Citem.setSelected(! Citem.isSelected());

            // Repaint cell

            jlist.repaint(jlist.getCellBounds(index, index));
         }
      });   

      Jframe.getContentPane().add(new JScrollPane(jlist));
      Jframe.pack();
       Jframe.setVisible(true);
   }
}

// Represents items in the list that can be selected

class CheckBoxItem
{
   private String  label;
   private boolean isSelected = false;

   public CheckBoxItem(String label)
   {
      this.label = label;
   }

   public boolean isSelected()
   {
      return isSelected;
   }

   public void setSelected(boolean isSelected)
   {
      this.isSelected = isSelected;
   }

   public String toString()
   {
      return label;
   }
}

// Handles rendering cells in the list using a check box

class CheckListRendererItm extends JCheckBox
   implements ListCellRenderer
{
   public Component getListCellRendererComponent(
         JList list, Object value, int index,
         boolean isSelected, boolean hasFocus)
   {
      setEnabled(list.isEnabled());
      setSelected(((CheckBoxItem)value).isSelected());
      setFont(list.getFont());
      setBackground(list.getBackground());
      setForeground(list.getForeground());
      setText(value.toString());
      return this;
   }
}

, ,

Comments are closed.