Java – JList – when you click a selected item, deselect it

If I click on the selected index on JList, I want it to be deselected In other words, clicking on the index actually switches their choices It doesn't seem to be supported like this, so I tried

list.addMouseListener(new MouseAdapter()
{
   public void mousePressed(MouseEvent evt)
   {
      java.awt.Point point = evt.getPoint();
      int index = list.locationToIndex(point);
      if (list.isSelectedIndex(index))
         list.removeSelectionInterval(index,index);
   }
});

The problem here is that JList is called after it has operated on the mouse event, so it deselects everything So I tried to delete all the mouselisteners of JList, add my own, and then add all the default listeners This doesn't work because JList will reselect the index after I deselect it Anyway, what I finally thought was

MouseListener[] mls = list.getMouseListeners();
for (MouseListener ml : mls)
   list.removeMouseListener(ml);
list.addMouseListener(new MouseAdapter()
{
   public void mousePressed(MouseEvent evt)
   {
      java.awt.Point point = evt.getPoint();
      final int index = list.locationToIndex(point);
      if (list.isSelectedIndex(index))
         SwingUtilities.invokelater(new Runnable()
         {
            public void run()
            {
               list.removeSelectionInterval(index,index);
            }
         });
   }
});
for (MouseListener ml : mls)
   list.addMouseListener(ml);

... and that job But I don't like it. Is there a better way?

Solution

Take a look at the example "listselectionmodel: enable switch selection mode":

I have modified the multi selection list box (changing setselectioninterval to addselectioninterval). If you click to cancel the selection when the mouse stops and move the mouse, you can eliminate the problem of reselection (moving gesture starts the check to add and remove)

objList.setSelectionModel(new DefaultListSelectionModel() {
    private static final long serialVersionUID = 1L;

    boolean gestureStarted = false;

    @Override
    public void setSelectionInterval(int index0,int index1) {
        if(!gestureStarted){
            if (isSelectedIndex(index0)) {
                super.removeSelectionInterval(index0,index1);
            } else {
                super.addSelectionInterval(index0,index1);
            }
        }
        gestureStarted = true;
    }

    @Override
    public void setValueIsAdjusting(boolean isAdjusting) {
        if (isAdjusting == false) {
            gestureStarted = false;
        }
    }

});
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>