Context Sensitive JTable (Part 2)
- by Geertjan
Now, having completed part 1, let's add a popup menu to the JTable. However, the menu item in the popup menu should invoke the same Action as invoked from the toolbar button created yesterday.
Add this to the constructor created yesterday:
Collection<? extends Action> stockActions =
Lookups.forPath("Actions/Stock").lookupAll(Action.class);
for (Action action : stockActions) {
popupMenu.add(new JMenuItem(action));
}
MouseListener popupListener = new PopupListener();
// Add the listener to the JTable:
table.addMouseListener(popupListener);
// Add the listener specifically to the header:
table.getTableHeader().addMouseListener(popupListener);
And here's the standard popup enablement code:
private JPopupMenu popupMenu = new JPopupMenu();
class PopupListener extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
showPopup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
showPopup(e);
}
private void showPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
}