如何在Java RCP应用程序中保留treeviewer的状态?

时间:2015-11-09 10:27:33

标签: swt eclipse-rcp rcp treeviewer

我有一个简单的RCP应用程序,其中有几个向导,其中一个有树查看器。我想在下次打开特定视图时保留树查看器中所选项目的状态。截至目前,我已经实现了使用静态变量并且工作正常。我想知道如何以更好的方式完成它?

//示例代码

private static RepositoryLocationItem lastRepoItemSelected;

Composite parent=new Composite(SWT.NONE)
treeViewer = new TreeViewer(parent);
treeViewer.setContentProvider(new MovingBoxContentProvider());
treeViewer.setLabelProvider(new MovingBoxLabelProvider());
treeViewer.setInput(getInitalInput());

treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {

/* Setting the value of lastRepoItemSelected */
});


if(lastRepoItemSelected !=null)
{
treeViewer.setSelection(new StructuredSelection(lastRepoItemSelected),true); 
}

1 个答案:

答案 0 :(得分:4)

假设这是一个3.x样式的RCP(您的视图扩展为ViewPart),您可以使用saveState方法保存您的视图状态:

@Override
public void saveState(final IMemento memento)
{
  // TODO set values in the 'memento'
}

然后,当再次显示视图时,您可以使用init方法从纪念品中恢复值:

@Override
public void init(final IViewSite site, final IMemento memento)
  throws PartInitException
{
  super.init(site, memento);

  // TODO restore from 'memento'
}

注意:Mementos会在重新启动RCP时保留,因此您需要在其中存储在RCP的新实例中有效的值。

另请查看Eclipse wiki entry以获取更多信息。

对于WizardPage,您可以使用IDialogSettings。您必须使用以下内容在Wizard中进行设置:

IDialogSettings pluginSettings = Activator.getDefault().getDialogSettings();
IDialogSettings wizardSettings = pluginSettings.getSection("id of your wizard");
if (wizardSettings == null) {
    wizardSettings= new DialogSettings("id of your wizard");
    pluginSettings.addSection(wizardSettings);
}
setDialogSettings(wizardSettings);

其中Activator是您的插件激活器类,“向导名称”是您的向导的ID(只要它在您的插件中是唯一的,就可以是任何内容)。

在向导页面中,您可以通过以下方式获取设置:

IDialogSettings settings = getDialogSettings();

IDialogSettings有许多方法可以保存和恢复各种值,例如:

settings.put("key", "string value");

String value = settings.get("key");