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,107
  • 18
  • 130
  • 305
itro
  • 6,698
  • 25
  • 72
  • 111
  • 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
  • 5,838
  • 6
  • 44
  • 68
Pavel K.
  • 436
  • 4
  • 10
1
Community
  • 1
  • 1
mKorbel
  • 109,107
  • 18
  • 130
  • 305
1

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

Durandal
  • 19,701
  • 3
  • 33
  • 65