Search code examples
javaswingmouseeventjpopup

Swing: mouse event on JTree or other components becomes skipped sometimes


I need to show popup-menu on my JTree, and I added mouse listener just like that:

  tree.addMouseListener(new MouseAdapter(){
     public void mouseClicked(MouseEvent me){
        if (SwingUtilities.isRightMouseButton(me)){
           //.. some code to show popup menu
        }
     }
  });

But sometimes this event is just skipped: I clicked, but mouseClicked() is not called. The same happens with JTabbedPane: i do right click on some tab, and sometimes mouseClicked() is not called, but tab becomes actually switched.

UPD: this happens in 10% of clicks, approximately. Too often to ignore it.

By the way, I can add ChangeListener on such JTabpedPane, and this event is never skipped, but i need to handle mouse too, and I have absolutely no idea what can be wrong here.

Any help is appreciated.


Solution

  • I guess that the problem is that in 10% of clicks you are not actually clicking but starting and finishing a drag. That is why mouseClicked event doesn't work.

    Try listening mousePressed or mouseReleased MouseAdapter's event (depends on what behavior you want) instead of mouseClicked event.