Eclipse: create preference page programmatically

天涯浪子 提交于 2019-11-30 22:12:44

Here is the java code, which allows the creation of a preference Page programmatically:


//create an instance of the custom MyPreference class
IPreferencePage page = new MyPreference(); 
page.setTitle("Custom Configurations");

//create a new PreferenceNode that will appear in the Preference window PreferenceNode node = new PreferenceNode("1", page);

//use workbenches's preference manager PreferenceManager pm= PlatformUI.getWorkbench().getPreferenceManager();

pm.addToRoot(node); //add the node in the PreferenceManager

Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();

//instantiate the PreferenceDialog PreferenceDialog pd = new PreferenceDialog(shell, pm);

//this line is important, it tell's the PreferenceDialog which preference-store it should write to pd.setPreferenceStore(Activator.getDefault().getPreferenceStore()); pd.create(); pd.open();

Finally I discovered That simply I can't do this by code using default preference page viewer!

So I realized an handler that load a PreferenceDialog everytime is called and every time create nodes and pages. that the only way I find and it works.

Answer given by Skip is almost right.

The exception is raised because, once the dialog is closed, page is removed from IPreferenceNode, but the node still remains in the PreferenceManager, thus it raises exception for not finding the page.

We must manually remove the nodes before adding the nodes to PreferenceManager.

pm.removeAll()

//create an instance of the custom MyPreference class
IPreferencePage page = new MyPreference(); 
page.setTitle("Custom Configurations");

//create a new PreferenceNode that will appear in the Preference window
PreferenceNode node = new PreferenceNode("1", page);

//use workbenches's preference manager
PreferenceManager pm= PlatformUI.getWorkbench().getPreferenceManager();

pm.removeAll(); // removes the previous nodes    
pm.addToRoot(node); //add the node in the PreferenceManager

Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();

//instantiate the PreferenceDialog
PreferenceDialog pd = new PreferenceDialog(shell, pm); 

//this line is important, it tell's the PreferenceDialog which preference-store it should write to
pd.setPreferenceStore(Activator.getDefault().getPreferenceStore());
pd.create();
pd.open();

This will work perfectly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!