NetBeans Platform Tip: Restore windows after restart

DZone 's Guide to

NetBeans Platform Tip: Restore windows after restart

· Java Zone ·
Free Resource
In last version 0.3.2 of Epictetus I've added new feature - restore opened windows and content after application restart. NetBeans Platform allows you to implement this feature in three easy steps.

Step 1. To save or not to save.

Look at the method getPersistenceType() of your TopComponent. This method returns one these values: PERSISTENCE_NEVER, PERSISTENCE_ONLY_OPENED, PERSISTENCE_ALWAYS. When application is closing platform checks all TopComponents in registry and according to the value of this method serialize them or not.
PERSISTENCE_NEVER - do not store and restore this component.
PERSISTENCE_ONLY_OPENED - restore it if component is opened in Mode.
PERSISTENCE_ALWAYS - always restore
Set persistence type to PERSISTENCE_ONLY_OPENED or PERSISTENCE_ALWAYS and your application will restore windows and even focus on the last active.

Step 2. Save your data.

For example, you have an editor inside your TopComponent and you want to restore text and caret position after start. In that case you need to override method writeExternal(ObjectOutput objectOutput).

public void writeExternal(ObjectOutput objectOutput) throws IOException
String text = editor.getText();
objectOutput.writeUTF(text != null ? text : "");

Step 3. Load your data.

Override method readExternal(ObjectInput objectInput) and read all saved data one by one:
public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException
int position = objectInput.readInt();
catch (IOException e)
System.out.println("Can't restore previously saved component " + getDisplayName());

You can make empty catch block and swallow exception but I wouldn't recomend that.

Remember, all restored windows are deserialized from application configuration directory. If you change the code of your TopComponent and then run the application the restored windows won't get your changes until you reopen them.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}