Search code examples
javaswingmouseevent

How can I call the mouse right click event in SwingGui?


I have a table. If I right-click I got a JPopUpMenu but before the pop-up I want to select the row where the right-click event is done. Here is what I've tried.

path_tbl.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            System.out.println(e.getPoint());

            Point point = e.getPoint();
            int selectedRow = path_tbl.rowAtPoint(point);
            path_tbl.setRowSelectionInterval(selectedRow, selectedRow);
        }
    });

In that event, I cannot get any output from the console when I right-click. However, when I left-click, points are printed to the console.

java.awt.Point[x=105,y=76]

So, this event only works when I left-click. How can I make this event work with right-click?


Solution

  • Since you want custom mouse behavior, you should not use setComponentPopupMenu.

    Instead, display the JPopupMenu yourself, using JPopupMenu’s show method:

    JPopupMenu menu = /* ... */;
    
    path_tbl.addMouseListener(new MouseAdapter() {
        private void showPopupMenuFor(MouseEvent e) {
            if (menu.isPopupTrigger(e)) {
                Point point = e.getPoint();
                int row = path_tbl.rowAtPoint(point);
    
                if (!path_tbl.isRowSelected(row)) {
                    path_tbl.setRowSelectionInterval(row, row);
                }
    
                menu.show(path_tbl, e.getX(), e.getY());
            }
        }
    
        @Override
        public void mousePressed(MouseEvent e) {
            showPopupMenuFor(e);
        }
    
        @Override
        public void mouseReleased(MouseEvent e) {
            showPopupMenuFor(e);
        }
    
        @Override
        public void mouseClicked(MouseEvent e) {
            showPopupMenuFor(e);
        }
    });
    

    You must check the MouseEvent in both mousePressed and mouseReleased, because exactly when a context menu is triggered depends on the platform and the look-and-feel. (Checking in mouseClicked may or may not be necessary, but it doesn’t hurt.)