view counter

Singleton/Non-Singleton TopComponent via Annotations

Thanks to Geertjan Wielenga for this story

This is a TopComponent with the annotations created by the New Window wizard:

view counter
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;

@TopComponent.Description(preferredID = "MySingletonTopComponent",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = true)
@ActionID(category = "Window", id = "org.test.module.MySingletonTopComponent")
@ActionReference(path = "Menu/Window")
@TopComponent.OpenActionRegistration(displayName = "#CTL_MySingletonAction",
preferredID = "MySingletonTopComponent")
@NbBundle.Messages({
    "CTL_MySingletonAction=MySingleton",
    "CTL_MySingletonTopComponent=MySingleton Window",
    "HINT_MySingletonTopComponent=This is a MySingleton window"
})
public class MySingletonTopComponent extends TopComponent {

     public MySingletonTopComponent() {

        setName(Bundle.CTL_MySingletonTopComponent());
        setToolTipText(Bundle.HINT_MySingletonTopComponent());

    }

}

However, I don't always want a singleton. So, if you change the annotations slightly, you have a non-singleton. All I did was remove the "preferredID" from the @TopComponent.OpenActionRegistration annotation (i.e., the bit you see in bold above) and now I can open multiple instances of the TopComponent below:
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;

@TopComponent.Description(preferredID = "MyInstanceTopComponent",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = true)
@ActionID(category = "Window", id = "org.test.module.MyInstanceTopComponent")
@ActionReference(path = "Menu/Window")
@TopComponent.OpenActionRegistration(displayName = "#CTL_MyInstanceTopComponentAction")
@Messages({
    "CTL_MyInstanceTopComponentAction=MyInstance",
    "CTL_MyInstanceTopComponent=MyInstance Window",
    "HINT_MyInstanceTopComponent=This is a MyInstance window"
})
public final class MyInstanceTopComponent extends TopComponent {

    public MyInstanceTopComponent() {

        setName(Bundle.CTL_MyInstanceTopComponent());
        setToolTipText(Bundle.HINT_MyInstanceTopComponent());

    }

}

Probably it means that the Action is unable to find the existing instance of the TopComponent, since it doesn't know its ID, and therefore creates a new one.

Read the entire article at its source

view counter