JList - deselect when clicking an already selected item

后端 未结 6 1762
忘掉有多难
忘掉有多难 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:10

    I extended FuryComptuers answer to support multiple selection, and fixed an issue where setSelectionInterval didn't work if it was called directly.

    public class ToggleableListSelectionModel extends DefaultListSelectionModel {
        private static final long serialVersionUID = 1L;
    
        private boolean mGestureStarted;
    
        @Override
        public void setSelectionInterval(int index0, int index1) {
            // Toggle only one element while the user is dragging the mouse
            if (!mGestureStarted) {
                if (isSelectedIndex(index0)) {
                    super.removeSelectionInterval(index0, index1);
                } else {
                    if (getSelectionMode() == SINGLE_SELECTION) {
                        super.setSelectionInterval(index0, index1);
                    } else {
                        super.addSelectionInterval(index0, index1);
                    }
                }
            }
    
            // Disable toggling till the adjusting is over, or keep it
            // enabled in case setSelectionInterval was called directly.
            mGestureStarted = getValueIsAdjusting();
        }
    
        @Override
        public void setValueIsAdjusting(boolean isAdjusting) {
            super.setValueIsAdjusting(isAdjusting);
    
            if (isAdjusting == false) {
                // Enable toggling
                mGestureStarted = false;
            }
        }   
    }
    

提交回复
热议问题