Create a new eclipse-rcp preference page by code when a listener is invoked

Objective:
-To create an eclipse-rcp preference page without using the preference extension, all is done in code. This is done by creating a customized button with a SelectionListener, and eventually that action will call a customized preference page.

How to do:
1.) create a new eclipse-rcp application with a view
2.) add a button in the view's createControl method
    -this button should have a SelectionListener attached which will be called onclick
public void createPartControl(Composite parent) {
    Button b = new Button(parent, SWT.NONE);
    b.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            //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); 
            PreferenceManager pm = new PreferenceManager();
            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 on what store to used
            pd.setPreferenceStore(Activator.getDefault().getPreferenceStore());
            pd.create();
            pd.open();
        }
    );
}


MyPreference class
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.irri.cril.jicis.administrator.Activator;

public class MyPreference extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
    
    public MyPreference() {
        super(GRID);
    }
    
    @Override
    public void init(IWorkbench workbench) {
        setPreferenceStore(Activator.getDefault().getPreferenceStore());
        setDescription("Custom Configuration");
    }

    @Override
    protected void createFieldEditors() {
        //FieldEditor types FieldEditor fields here
        addField(new StringFieldEditor("NAME", "Name:", getFieldEditorParent()));
    }
}


This code can now save and retrieve values in your default preference store. if you want to override the ok, cancel, default, etc actions, you can add on the MyPreference class.
Create a new eclipse-rcp preference page by code when a listener is invoked Create a new eclipse-rcp preference page by code when a listener is invoked Reviewed by czetsuya on Wednesday, November 25, 2009 Rating: 5

1 comment:

Skip said...

Thank you, it worked!

Powered by Blogger.