Search code examples
javacheckboxjlist

How to add a custom checkbox into JList (Java)?


This is how the program looks:

https://i.sstatic.net/zOFCh.png

This is how I want it to look:

https://i.sstatic.net/XTdlJ.png

As you can see in the picture I have tried a bit and learned that I need to use ListCellRenderer, but the problem is i have created 2 custom png files

  1. checked.png and

  2. unchecked.png

when I click daily goals #1 it should give state = true and checked.png should appear and stay checked unless I click it again. Unchecked.png could be standard on the jList column.

I also want to place my checkbox 1 cm to the left of the end of the row (padding) not sure hows its done in java sadly. (You'll understand better by looking at the picture)

After looking through some guides I have learned that the only way to add extra stuff to a JList column is by using ListCellRenderer. I have tried quite a while with no success so thought of asking others. Does anyone have any ideas on how to do this?

The thought was to get it to work then display in a JTable by changing the Jtable column to Daily goals and displaying X to indicate the goal was achieved. But I think I should be able to do this, The main question is the custom checkbox implementation.


Solution

    1. You can have two types of checkboxes to be used as jlist cell renderers, one for selected cells, another for unselected.
    2. Use ImageIcon to decorate the checkbox with your images.
    3. In your jlist cell render you need to have logic to return the intended checkbox to render that list cell.
    4. Note to override the text in the checkbox to the actual list cell value

      public class TestFrame extends JFrame {
      ImageIcon iconChecked = new ImageIcon(TestFrame.class.getResource("checked.png"));
      ImageIcon iconUnchecked = new ImageIcon(TestFrame.class.getResource("unchecked.png"));
      JList jList = new JList(new Object[]{"ABC", "123"});
      
      public TestFrame() {
          this.add(jList);
          jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      
      jList.setCellRenderer(new ListCellRenderer() {
          @Override
          public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
              for (int i : list.getSelectedIndices()) {
                  if (index == i) {
                      JCheckBox checkBoxChecked = new JCheckBox(value.toString(), iconChecked);
                      return checkBoxChecked;
                  }
              }
      
              JCheckBox checkBoxUnchecked = new JCheckBox(value.toString(), iconUnchecked);
              return checkBoxUnchecked;
          }
      });
      }}