Right-Clicking Tables in Swing

January 2nd, 2009

A lot of the data in CodeTurtle is tabular. Inevitably, I ended up wanting to have a right-click menu for operations on a particular row. The problem is, the default behavior for a JTable doesn’t automatically select the row under the cursor on a right-click. After a bit of poking around, the solution was pretty simple. The following example is a mouse adapter assigned to the table itself. The purpose of this particular implementation is to display a popup menu under the cursor for operations on the selected row. This code allows the user to right-click any row to both select it and then display the menu of operations to execute against it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private class PopupMenuListener extends MouseAdapter {
  public void mousePressed(MouseEvent e) {
    showPopup(e);
  }
 
  public void mouseReleased(MouseEvent e) {
    showPopup(e);
  }
 
  private void showPopup(MouseEvent e) {
 
    if (e.isPopupTrigger()) {
 
      // Select the row under the cursor so we know
      // which to edit or delete
      Point p = e.getPoint();
      int rowNumber = rowAtPoint(p);
      ListSelectionModel model = getSelectionModel();
      model.setSelectionInterval(rowNumber, rowNumber);
 
      // Display the popup 
      popupMenu.show(e.getComponent(),
          e.getX(), e.getY());
    }
 
  }
}

This can be seen in action (at least as of the time of writing) in the CommentsTable.java file.

Comments are closed.