1

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());
           }
       }
   });
mKorbel
  • 109,525
  • 20
  • 134
  • 319
itro
  • 7,006
  • 27
  • 78
  • 121
  • Why not add a popupmenu to the mouse wheel too? would be fun I guess. Anyway, back to seriousness, why would you want to do that? – Adel Boutros Jun 29 '12 at 13:46

3 Answers3

4
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());
       }
   }
});
George
  • 6,006
  • 6
  • 48
  • 68
Pavel K.
  • 436
  • 4
  • 11
1
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

You can determine the clicked row easily enough using JTable.rowAtPoint(event.getPoint()) in your mouse listener.

Durandal
  • 19,919
  • 4
  • 36
  • 70