Platinum Partner
java,netbeans,lifecyclemanager

How to Create a Custom NetBeans Platform LifecycleManager

One of the things we need when we develop a desktop application is closing control: "What should our application do if we press the exit button? Should we save our work? Should we confirm the exit? Or should we just close the application and lose everything?"

If you are using the NetBeans Platform, it is possible that you have found yourself in this dilemma. The solution is VERY simple.

First, we need to create a class with an annotation for overriding the NetBeans Platform's default org.openide.LifecycleManager. Call the class "MyLifeCycleManager" and then annotate the class as follows:

@ServiceProvider(service=LifecycleManager.class, position=1)

Then we need to add the code for our class, for example:

@ServiceProvider(service=LifecycleManager.class, position=1)
public class MyLifecycleManager extends LifecycleManager {

@Override
public void saveAll() {
}

@Override
public void exit() {
Set<Topcomponent> tcs = TopComponent.getRegistry().getOpened();
Iterator<Topcomponent> it = tcs.iterator();
while (it.hasNext()) {
TopComponent tc = it.next();
if (tc instanceof DepartmentEditorTopComponent) {
tc.close();
}
}
Collection c = Lookup.getDefault().lookup(new Lookup.Template(LifecycleManager.class)).allInstances();
for (Iterator i = c.iterator(); i.hasNext();) {
LifecycleManager lm = (LifecycleManager) i.next();
if (lm != this) {
lm.exit();
}
}
}

}

And this is how it looks in the IDE:

When we extend "LifecycleManager", we need to implement the "exit" method and it is in that implementation where we code what we want to do before closing our application. In this case, I worry about closing properly a TopComponent I made (DepartmentTopComponent, from my Home Automation Application). You MUST write the following piece of code in the last part of exit method, so that your application can close properly (System.exit(0) will not work):

Collection c = Lookup.getDefault().lookup (new Lookup.Template (LifecycleManager.class)).allInstances();
for (Iterator i=c.iterator(); i.hasNext();) {
LifecycleManager lm = (LifecycleManager) i.next();
if (lm != this) {
lm.exit();
}
}

With that, you have your own implementation of LifecycleManager and you can provide specific things that need to be done before closing your application.

 

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}