Revision as of 15:53, 2 December 2009 by Rmichalsky (Talk | contribs)

How do I add an action to the global popup menu of tabs?

While there is no official way to add a custom action to a foreign TopComponent's tab, you can achieve this by installing a hook into the Swing event dispatch thread and listening for the popup activation. Then when the popup is detected, copy the actions from the TopComponent, add your custom actions, and finally set a new popup menu for that particular TopComponent.

// Install hook into the AWT event dispatch thread so we can capture context popup
private void addGlobalContextAction() {
    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
        public void eventDispatched(AWTEvent event) {
            MouseEvent mouseEvent = (MouseEvent) event;
            if (mouseEvent.isPopupTrigger()) {
                if (mouseEvent.getSource() instanceof TabDisplayer) {

                    // Find the TopComponent being wrapped
                    TabDisplayer tabDisplayer = (TabDisplayer) mouseEvent.getSource();
                    TabData tabData = tabDisplayer.getModel().getTab(
                    TopComponent tc = (TopComponent) tabData.getComponent();

                    // Copy existing popup-menu
                    JPopupMenu popup = new JPopupMenu();
                    boolean separatorJustAdded = false;
                    for (Action action : tc.getActions()) {
                        if (action == null) {
                            if (!separatorJustAdded) {
                                separatorJustAdded = true;
                        } else if (action.isEnabled() &&
                                   !(action instanceof FileSystemAction)) {
                            JMenuItem wrappedAction = new JMenuItem(action);
                            separatorJustAdded = false;

                    // Add custom action
                    popup.add(new AbstractAction("Click me") {
                        public void actionPerformed(ActionEvent e) {
                            System.out.println("Yay, you clicked me!");

private String removeAmpersand(Object actionName) {
    return ((String) actionName).replaceAll("&", "");

Notice however, there are some ugly action filtering going on and keyboard accelerator indications have to be removed from the action text. Furthermore, it's relatively expensive to add such an application-wide hook. As such, this is to be considered a fragile hack until a better solution becomes available.

Applies to: NetBeans IDE 6.5 and above Platforms: All

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo