javaswingjtablemouseleftbuttondownjpopup

How to adapt left-click action on JTable to the right-click in java?


I have a JTable which I want to have left-click and right-click JPopupMenu on it. Normaly by left-click on the JTable you can select a row. I would like to do the same with right-click plus show up a popup menu. Does anybody know how to do this?

table.addMouseListener(new MouseAdapter() {
       @Override
       public void mouseClicked(MouseEvent e) {
           if (SwingUtilities.isRightMouseButton(e)) {
               //this line gives wrong result because table.getSelectedRow() stay alwase on the same value
               codeModel.setSelectedFileName(table.getValueAt(table.getSelectedRow(), 0).toString());
               JPopupMenu popup = createRightClickPopUp();
               popup.show(e.getComponent(), e.getX(), e.getY());
           }else{
               codeModel.setSelectedFileName(table.getValueAt(table.getSelectedRow(), 0).toString());
               codeTextArea.setText(codeModel.getCodeContents());
           }
       }
   });

Solution

  • table.addMouseListener(new MouseAdapter() {
       @Override
       public void mouseClicked(MouseEvent e) { //or mouseReleased(MouseEvent e)
           if (SwingUtilities.isRightMouseButton(e)) {
               //-- select a row
               int idx = table.rowAtPoint(e.getPoint());
               table.getSelectionModel().setSelectionInterval(idx, idx);
               //---
               codeModel.setSelectedFileName(table.getValueAt(table.getSelectedRow(), 0).toString());
               JPopupMenu popup = createRightClickPopUp();
               popup.show(e.getComponent(), e.getX(), e.getY());
           }else{
               codeModel.setSelectedFileName(table.getValueAt(table.getSelectedRow(), 0).toString());
               codeTextArea.setText(codeModel.getCodeContents());
           }
       }
    });