简体   繁体   中英

How to read Checkboxes status in Jlist

I am developing a GUI where I have included some Checkboxes into a Jlist but I cannot read their status. Below i have an example of my code

final JScrollPane scrollPaneWat = new JScrollPane();
        scrollPaneWat.setBounds(526, 248, 152, 140);
        Pane.add(scrollPaneWat);
        scrollPaneWat.hide();

        @SuppressWarnings("unchecked")
        final JList<?> list = new JList(new CheckListRendererClasses[] {
                new CheckListRendererClasses("a"),
                new CheckListRendererClasses("b"),
                new CheckListRendererClasses("c"),
                new CheckListRendererClasses("d"),
                new CheckListRendererClasses("e"),
                new CheckListRendererClasses("f"),
                new CheckListRendererClasses("g"),
        scrollPaneWat.setViewportView(list);
        list.setBackground(Color.LIGHT_GRAY);
        list.setFont(new Font("Times New Roman", Font.ITALIC, 14));

        list.setCellRenderer(new CheckListRenderer());
          list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
          list.addMouseListener(new MouseAdapter(){
             public void mouseClicked(MouseEvent event){
                JList list = (JList) event.getSource();
                int index = list.locationToIndex(event.getPoint());
                CheckListRendererClasses item = (CheckListRendererClasses)
                   list.getModel().getElementAt(index);
                item.setSelected(! item.isSelected());
                list.repaint(list.getCellBounds(index, index));
             }
          });

I have tried this:

for (int i = 0; i < 7; i++) {

    Object sel = list.getModel().getElementAt(i);

    System.out.print(sel.toString());
}

and I get back a, b, c, d, e, f, g

Also, when i tried this:

System.out.println(list.isSelectedIndex(1));

if I tick the Checkbox a, it prints true. But if the Checkbox a is ticked and I tick one more (so now I have ticked the Checkbox a and c) it returns false.

It's like it keeps my last choice.

What I want is, for example if I have ticked the a, c, d Checkboxes to be able to make a for loop and see everytime if a checkbox at value i is ticked or not.

Thank you

ListSelectionModel.SINGLE_SELECTION更改为MULTIPLE_INTERVAL_SELECTION以一次允许多个选择。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM