szolo
szolo

Reputation: 247

Save state between closening/opening intro part

I have Eclipse RCP application. My own IntroPart extends org.eclipse.ui.part.IntroPart.

Through inheritance I got this method:

@Override
public void saveState(IMemento memento) {
}

Here it is stated that when the workbench is shut down, the method saveState is called on all open views. But this is true only if I close my whole application.

What should I do, to save the intro page state before if I close only this page, not the hole application?

Upvotes: 2

Views: 1496

Answers (1)

Modus Tollens
Modus Tollens

Reputation: 5123

Your link to the FAQ answers that:

Another mechanism for persisting view state is the JFace IDialogSettings facility. The advantage of dialog settings over the view save/init mechanism is that you can control when settings are persisted.

This is an example on how to use IDialogSettings to persist the state of an IntroPart when it is closed and how to restore it when it is created. MyIntroPart is an IntroPart that has a Text widget. The displayed text is saved when the IntroPart is closed and restored when it is created.

To get the partClosed event, MyIntroPart implements IPartListener2 and registers itself with the PartService.

private static final String MY_INTRO_SETTINGS = "my_intro_settings";
private static final String MY_INTRO_TEXT_KEY = "my_intro_text";

@Override
public void createPartControl(Composite parent) {
    this.text = new Text(parent, SWT.BORDER);

    // try to load the settings
    IDialogSettings settings = Activator.getDefault().getDialogSettings();
    IDialogSettings section = settings.getSection(MyIntroPart.MY_INTRO_SETTINGS);
    if (section != null) {
        // set the restored text string in the text widget
        this.text.setText(section.get(MyIntroPart.MY_INTRO_TEXT_KEY));
    }

    // register the part listener
    getIntroSite().getWorkbenchWindow().getPartService().addPartListener(this);
}

This will restore the text to the text widget.

MyIntroPart implements partClosed of IPartListener2 to save dialog settings when the view is closed:

@Override
public void partClosed(IWorkbenchPartReference partRef) {
    // remove part listener from part service
    getIntroSite().getWorkbenchWindow().getPartService().removePartListener(this);

    IDialogSettings settings = Activator.getDefault().getDialogSettings();

    // get the section of the text
    IDialogSettings section = settings.getSection(MyIntroPart.MY_INTRO_SETTINGS);

    // if it doesn't exist, create it
    if (section == null) {
        section = settings.addNewSection(MyIntroPart.MY_INTRO_SETTINGS);
    }

    // put text from text field in section
    section.put(MyIntroPart.MY_INTRO_TEXT_KEY, this.text.getText());
}

Thanks to fredrik for pointing out that no loading from or saving to a file is required here.

Upvotes: 3

Related Questions