How do i add an icon to the context menu?

Apache NetBeans Wiki Index

Note: These pages are being reviewed.

This is not recommended for NB RCP (it will break HMI standards on Mac OS X for example), but is still possible.


  • let your action implement Presenter.Popup and return a JMenuItem instance for the current action (see [1], [2])

  • set the icon via putValue(javax.swing.Action.SMALL_ICON, …​)

  • set the icon via putValue("iconBase", …​) to make it work properly in the toolbar. Otherwise you will get a fixed size icon.

  • By using setEnabled, it makes sure every listener will be notified (JButton, JMenuItem…​). Moreover it is safer to call it on the EDT since it is not sure which thread triggered the event in the first place.

        category = "Build",
        id = "sample.contextmenu.HelloIconAction")
    @ActionReference(path = "Menu/File", position = 0),
    @ActionReference(path = "Loaders/Languages/Actions", position = 0),
        displayName = "#CTL_HelloIconAction")

@Messages("CTL_HelloIconAction=Hello Icon Action")
public final class HelloIconAction extends AbstractAction implements Presenter.Popup {

    private static final String ICON = "sample/contextmenu/sample.gif";
    private static final long serialVersionUID = 1L;
    private final LookupListener lookupListener;
    private final Lookup.Result<Project> result;

    public HelloIconAction() {
        putValue(SMALL_ICON, ImageUtilities.loadImageIcon(ICON, false));
        putValue(NAME, Bundle.CTL_HelloIconAction());
        putValue("iconBase", ICON);
        result = Utilities.actionsGlobalContext().lookupResult(Project.class);
        this.lookupListener = new LookupListener() {

            public void resultChanged(LookupEvent ev) {
                EventQueue.invokeLater(new Runnable() {

                    public void run() {
        result.addLookupListener(WeakListeners.create(LookupListener.class, this.lookupListener, result));

    public void actionPerformed(ActionEvent ev) {
        for (Project project : result.allInstances()) {
           JOptionPane.showMessageDialog(null, "Hello colorful project.\n" + project.toString());

    public JMenuItem getPopupPresenter() {
        return new JMenuItem(this);