Link to home
Start Free TrialLog in
Avatar of csound
csound

asked on

Adding JCheckBox into JList

I am trying to put JCheckBox into JList.

What I want is

1 When a check box is clicked, it automatically changes its state
2 Get all the check boxes in the list whose states are  ‘selected’.

The following is my attempt to do it.

At the moment when I click on a check box it turns itself on and then it quickly turns itself off.
Also, I can not get all the check boxes whose states are ‘selected’.


private final Component[] stats_option={new JCheckBox("1"), new JCheckBox("2"), new JCheckBox("3"), new JCheckBox("4"), new JCheckBox("5")};
 
GUITest()
  {
    JList list=new JList(stats_option);
    list.setVisibleRowCount(3);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.addListSelectionListener(new
                                    ListSelectionListener()
                                    {
      public void valueChanged(ListSelectionEvent evt)
      {  
        JList list=(JList)evt.getSource();
        JCheckBox check= (JCheckBox)list.getSelectedValue();
       
        if(check.isSelected())
        {
          check.setSelected(false);
        }
        else
        {
          check.setSelected(true);
        }
      }
     
    });
    list.setCellRenderer(new Stats_cell_renderer());
    JScrollPane scroll=new JScrollPane(list);
   
    add(scroll);
  }
 
  class Stats_cell_renderer implements ListCellRenderer
  {  
    public Component getListCellRendererComponent(JList list, Object value, int index,
                                                  boolean isSelected, boolean cellHasFocus)
    {  
      JCheckBox check=(JCheckBox)value;
      //check.setText((String)value);
      background = isSelected ? list.getSelectionBackground() : list.getBackground();
      foreground = isSelected ? list.getSelectionForeground() : list.getForeground();
      check.setBackground(background);
      check.setForeground(foreground);
      return check;
    }
   
    public Dimension getPreferredSize()
    {  
     
      return new Dimension(100, 50);
    }
   
    private Color background;
    private Color foreground;
  }
 
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial