JList - deselect when clicking an already selected item

后端 未结 6 1756
忘掉有多难
忘掉有多难 2020-12-10 04:36

If a selected index on a JList is clicked, I want it to de-select. In other words, clicking on the indices actually toggles their selection. Didn\'t look like this was suppo

6条回答
  •  情书的邮戳
    2020-12-10 05:09

    How about this?

    import javax.swing.DefaultListSelectionModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.ListSelectionModel;
    
    public class A {
        public static void main(String[] args) {
            JFrame f = new JFrame("Test");
            final JList list = new JList(new String[] {"one","two","three","four"});
            list.setSelectionModel(new DefaultListSelectionModel(){
    
    
                @Override
                public void setSelectionInterval(int index0, int index1) {
                    if (index0==index1) {
                        if (isSelectedIndex(index0)) {
                            removeSelectionInterval(index0, index0);
                            return;
                        }
                    }
                    super.setSelectionInterval(index0, index1);
                }
    
                @Override
                public void addSelectionInterval(int index0, int index1) {
                    if (index0==index1) {
                        if (isSelectedIndex(index0)) {
                            removeSelectionInterval(index0, index0);
                            return;
                        }
                    super.addSelectionInterval(index0, index1);
                    }
                }
    
            });
            f.getContentPane().add(list);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setVisible(true);
        }
    
    }
    

    It works but note one side effect... If you set the mode to multi selction like this for instance:

    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION );
    

    you cannot select multiple objects via mouse drag. Ctrl (or shift) click works. I'm sure it can be fixed but i assume you asked this for single selection lists... If not modify your question and we can start thinking for solutions to the multiple selection problem.

提交回复
热议问题