Home > NetBeans Platform, Uncategorized > NetBeans Platform Tip #2: Persisting state in TopComponents

NetBeans Platform Tip #2: Persisting state in TopComponents

Given the fact that NetBeans remembers the size, location, and layout of all your TopComponents, it isn’t too surprising that there is an easy mechanism for persisting state information.  Unfortunately it’s not immediately obvious; if you don’t stumble onto the right resources, you might be led to believe you need to deal with the Preferences API or writing to a database or some other flat file, and reading it later.  Fortunately it’s easier than that.  Assume we have a list of Strings we want to remember between invocations of our top component; somehow we get them from the user (the details of that are not important here), and we’d like to remember them.  The secret is in the writeExternal and readExternal methods, which are called when the TopComponent is serialized (saved) and deserialized (loaded).  Also make sure the persistence type you return is TopComponent.PERSISTENCE_ALWAYS; otherwise NetBeans will not attempt to save your TopComponent between invocations of your app.

public class TestTopComponent extends TopComponent implements Serializable {

    private List<String> strings = new ArrayList<String>();

    public EngineeringTableTopComponent(Collection<String> toSave) {

    public EngineeringTableTopComponent() {

    public void initComponents() {
         // Create GUI

    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;

     * Save the state of the top component, including which properties are displayed
     * @param oo
     * @throws IOException
    public void writeExternal(ObjectOutput oo) throws IOException {
        Object toWrite = new NbMarshalledObject(strings);

     * Restore the state of the top component, including which properties are displayed
     * @param oi
     * @throws IOException
     * @throws ClassNotFoundException
    public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException {
        NbMarshalledObject obj = (NbMarshalledObject) oi.readObject();
        strings  = (List<String>) obj.get();
  1. i82much
    December 9, 2010 at 4:03 pm

    It looks like this method no longer works (according to comments I’ve seen). It’s not ideal, but you can use writeProperties and readProperties instead: http://forums.netbeans.org/ptopic29908.html

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: