Context Sensitive JTable (Part 2)

Posted by Geertjan on Oracle Blogs See other posts from Oracle Blogs or by Geertjan
Published on Sun, 20 Nov 2011 04:42:27 -0600 Indexed on 2011/11/20 18:12 UTC
Read the original article Hit count: 196

Filed under:

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());
        }
    }
}

© Oracle Blogs or respective owner

Related posts about /NetBeans IDE