Back to top

vogella training Training Books

Eclipse Preferences - Tutorial

Lars Vogel

Version 1.7

25.01.2012

Revision History
Revision 0.1 25.06.2009 Lars
Vogel
Created
Revision 0.2 - 1.7 15.09.2010 - 25.01.2012 Lars
Vogel
bug fixes and enhancements

Eclipse Preferences

This article describes the usage of Eclipse preferences and preference pages. Within this tutorial Eclipse 3.7 (Indigo) is used.


Table of Contents

1. Eclipse Preferences
1.1. Preferences and Scopes
1.2. Eclipse Preference API
1.3. Setting preferences via plugin_customization.ini
2. Preference handling in Eclipse 4.
3. Preference handling in Eclipse 3.x
3.1. Preference Page
3.2. Secure storage of preferences
3.3. Access Preferences in different plug-ins
3.4. Reacting to changes in the preferences
4. Assumptions
5. Tutorial: Preferences via code
6. Tutorial: Preference Page
7. Tutorial: Secure storage of preferences
8. Thank you
9. Questions and Discussion
10. Links and Literature
10.1. Source Code
10.2. vogella Resources

1. Eclipse Preferences

1.1. Preferences and Scopes

Preferences are key / value pairs, where the key is an arbitrary name for the preference. The value can be a boolean, string, int or another primitive type. For example a user name might be stored via a key called user . The actual value for this key might be "Lars Vogel".

Eclipse Preferences are based on the Preferences class from the org.osgi.service.prefs package. Eclipse Preferences are very similar to standard Java Preferences with some support of additional features. They use the Eclipse framework to save and retrieve the configuration.

The Eclipse runtime defines three so-called scopes. The scope defines how the preference data is stored and how it is changeable.

Table 1. Eclipse Preference scope

Scope Description
Instance scope If the user runs the same program twice, the settings between the two programs may be different.
Configuration scope If the user runs the same program twice then the settings between the two programs are the same.
Default scope Default values which can not be changed. Supplied via configuration files in plug-ins and product definitions.


1.2. Eclipse Preference API

You can create and manipulate preferences directly in your coding. Preferences are read and saved by get() and put() methods. In the get() method you specify a default value in case the key can not be found. The clear() method allows to delete a preference value.

// We access the Configuration Scope
Preferences preferences = ConfigurationScope.INSTANCE
  .getNode("de.vogella.preferences.test");

Preferences sub1 = preferences.node("node1");
Preferences sub2 = preferences.node("node2");
sub1.put("h1", "Hello");
sub1.put("h2", "Hello again");
sub2.put("h1", "Moin");
try {
  // Forces the application to save the preferences
  preferences.flush();
  } catch (BackingStoreException e) {
    e.printStackTrace();
  }
} 

// Read values from the configuration scope
Preferences preferences = ConfigurationScope.INSTANCE
  .getNode("de.vogella.preferences.test");
Preferences sub1 = preferences.node("node1");
Preferences sub2 = preferences.node("node2");
sub1.get("h1", "default");
sub1.get("h2", "default");
sub2.get("h1", "default"); 

1.3. Setting preferences via plugin_customization.ini

You can use a file to set certain preference values. This files needs to get registered via the preferenceCustomization property on your product extension point. This file is typically named plugin_customization.ini.

Referring to the plugin_customization.ini file in the product extension

The format to use is <plugin id>/<setting>=<value>, e.g. de.vogella.test.preference/check=true.

To find the right values, just start your Eclipse application, switch to the .metadata directory in your workspace directory (by default the directory your application is starting in) and search for files ending with .pref.

2. Preference handling in Eclipse 4.

The following describes how to work with Preferences in Eclipse 3.x. See Eclipse 4 Preferences for working with Preference in Eclipse 4.

3. Preference handling in Eclipse 3.x

3.1. Preference Page

Eclipse 3.x provides an standard user interface to display and change preference values via a Preference dialog

To add a page to this Preference user interface a plug-in must contribute to the org.eclipse.ui.preferencePages extension point.

This extension point defined a class which is responsible for creating a user interface and storing the preference values. This class must implement IWorkbenchPreferencePage and must have a non-parameter constructor.

The PreferencePage class or one of its subclasses can get extended; a good template is usually FieldEditorPreferencePage.

To open the Preference dialog you can use the org.eclipse.ui.window.preferences command.

3.2. Secure storage of preferences

Eclipse allows to encrypt preference values via the org.eclipse.equinox.security plug-in.

The key/ value pairs will be stored in the file "secure.storage" in the folder ".eclipse/org.eclipse.equinox.security" of the user directory. Eclipse uses a class of type PasswordProvider for encrypting the preferences and has a default class registered.

Via the org.eclipse.equinox.security.secureStorage extension point you can register your own PasswordProvider.

3.3. Access Preferences in different plug-ins

You can access preferences in other plug-ins via the PreferenceService service.

For example, to access the "MySTRING1" preference in the "de.vogella.preferences.page" plug-in you can use the following:

String text = Platform.getPreferencesService().
  getString("de.vogella.preferences.page", "MySTRING1", "hello", null); 

3.4. Reacting to changes in the preferences

You can register IPropertyChangeListener to the preferences. The listener will be called by the Eclipse framework once the Preference Value changes.

Activator.getDefault().getPreferenceStore()
  .addPropertyChangeListener(new IPropertyChangeListener() {
    @Override
    public void propertyChange(PropertyChangeEvent event) {
      if (event.getProperty() == "MySTRING1") {
        String value = event.getNewValue().toString()
        // do something with the new value
      }
    }
  }); 

4. Assumptions

The following assumes that you know how to create simple Eclipse RCP applications and that you know how to create commands and add them to the menu. Please see the Eclipse RCP and the Eclipse Commands tutorials .

5. Tutorial: Preferences via code

You can create, store and retrieve preference values directly via your coding. The following gives an example for this. Create an Eclipse composite with three buttons. Use this composite in one of your parts (View or Editor).

The first Button will set the preference values. The next will display the values and the last will clear the preference values.

package de.vogella.preferences.test.ui;

import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;

public class ButtonComposite extends Composite {

  public ButtonComposite(Composite parent, int style) {
    super(parent, style);
    Button write = new Button(parent, SWT.PUSH);
    write.setText("Write");
    write.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {

        Preferences preferences = ConfigurationScope.INSTANCE
            .getNode("de.vogella.preferences.test");
        Preferences sub1 = preferences.node("node1");
        Preferences sub2 = preferences.node("node2");
        sub1.put("h1", "Hello");
        sub1.put("h2", "Hello again");
        sub2.put("h1", "Moin");

        try {
          // Forces the application to save the preferences
          preferences.flush();
        } catch (BackingStoreException e2) {
          e2.printStackTrace();
        }
      }
    });
    Button read = new Button(parent, SWT.PUSH);
    read.setText("Read");
    read.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
        Preferences preferences = ConfigurationScope.INSTANCE
            .getNode("de.vogella.preferences.test");
        Preferences sub1 = preferences.node("node1");
        Preferences sub2 = preferences.node("node2");
        System.out.println(sub1.get("h1", "default"));
        System.out.println(sub1.get("h2", "default"));
        System.out.println(sub2.get("h1", "default"));

      }
    });

    Button clear = new Button(parent, SWT.PUSH);
    clear.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
        Preferences preferences = ConfigurationScope.INSTANCE
            .getNode("de.vogella.preferences.test");
        Preferences sub1 = preferences.node("node1");
        Preferences sub2 = preferences.node("node2");
        // Delete the existing settings
        try {
          sub1.clear();
          sub2.clear();
          preferences.flush();
        } catch (BackingStoreException e1) {
          e1.printStackTrace();
        }
      }
    });
    clear.setText("clear");
  }
} 

Run and test your program.

6. Tutorial: Preference Page

The following will create a project with a preference pages which allows the user to maintain certain settings. Create a new RCP project de.vogella.preferences.page. Make sure you flag the "Generate an activator..." during the project creation. Use the "RCP application with a view" as a template.

Go to plugin.xml and add the extension org.eclipse.ui.preferencePages with the following settings.

Maintain the following code for your class "MyPreferencePage1". Method init() sets the preference store and the method createFieldEditors() registers pre-defined editors for values. checkState() allows to perform a validations. To get notified about value changes you to override the propertyChange method.

package de.vogella.preferences.page.preferencepage;

import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.DirectoryFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.RadioGroupFieldEditor;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

import de.vogella.preferences.page.Activator;

public class MyPreferencePage1 extends FieldEditorPreferencePage implements
    IWorkbenchPreferencePage {

  public MyPreferencePage1() {
    super(GRID);

  }

  public void createFieldEditors() {
    addField(new DirectoryFieldEditor("PATH", "&Directory preference:",
        getFieldEditorParent()));
    addField(new BooleanFieldEditor("BOOLEAN_VALUE",
        "&An example of a boolean preference", getFieldEditorParent()));

    addField(new RadioGroupFieldEditor("CHOICE",
        "An example of a multiple-choice preference", 1,
        new String[][] { { "&Choice 1", "choice1" },
            { "C&hoice 2", "choice2" } }, getFieldEditorParent()));
    addField(new StringFieldEditor("MySTRING1", "A &text preference:",
        getFieldEditorParent()));
    addField(new StringFieldEditor("MySTRING2", "A &text preference:",
        getFieldEditorParent()));
  }

  @Override
  public void init(IWorkbench workbench) {
    setPreferenceStore(Activator.getDefault().getPreferenceStore());
    setDescription("A demonstration of a preference page implementation");
  }
} 

To display the preference page you can use the standard Eclipse command "org.eclipse.ui.window.preferences". Add this to your menu, it will show the preference dialog.

Run the application and check that you can open your preference page via the menu. Validate that maintained values are stored even if you re-start your application.

Add a command "showPreferenceValues" with the following handler to the menu. This command demonstrates how to access preferences values from the preferencePage.

package de.vogella.preferences.page.handler;

import org.eclipse.core.commands.AbstractHandler;

public class ShowPreferenceValues extends AbstractHandler {

  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    Shell shell = HandlerUtil.getActiveWorkbenchWindowChecked(event)
        .getShell();
    String myPrefString = Activator.getDefault().getPreferenceStore()
        .getString("MySTRING1");
    MessageDialog.openInformation(shell, "Info", myPrefString);
    Boolean myPrefBoolean = Activator.getDefault().getPreferenceStore()
        .getBoolean("BOOLEAN_VALUE");
    // RadioGroupFieldEditor can get access
    String choice = Activator.getDefault().getPreferenceStore().getString("CHOICE");
    System.out.println(choice);
    MessageDialog.openInformation(shell, "Info", myPrefBoolean.toString());
    // I assume you get the rest by yourself
    return null;
  }

} 

To set the default values for preferences use the extension point "org.eclipse.core.runtime.preferences". Create a new initializer with the following class "de.vogella.preferences.page.preferencepage.MyInitializer".

package de.vogella.preferences.page.preferencepage;

import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;

import de.vogella.preferences.page.Activator;

public class MyInitializer extends AbstractPreferenceInitializer {

  public MyInitializer() {
  }

  @Override
  public void initializeDefaultPreferences() {
    IPreferenceStore store = Activator.getDefault().getPreferenceStore();
    store.setDefault("MySTRING1", "http://www.vogella.com");
  }

} 

Finally change the class "View" to the following to show one of the preference values. We also register a PropertyChangeListener to the preference store to get informed in case the preference settings change.

package de.vogella.preferences.page;

import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;

public class View extends ViewPart {

  private Label label;

  public void createPartControl(Composite parent) {
    IPreferenceStore preferenceStore = Activator.getDefault()
        .getPreferenceStore();
    String string = preferenceStore.getString("MySTRING1");

    label = new Label(parent, SWT.NONE);
    label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false,
        false));
    label.setText(string);
    // Add change listener to the preference store so that we are notified
    // in case of changes
    Activator.getDefault().getPreferenceStore()
        .addPropertyChangeListener(new IPropertyChangeListener() {
          @Override
          public void propertyChange(PropertyChangeEvent event) {
            if (event.getProperty() == "MySTRING1") {
              label.setText(event.getNewValue().toString());
            }
          }
        });
  }

  public void setFocus() {
  }
} 

7. Tutorial: Secure storage of preferences

To test the secure storage of preferences create the project "de.vogella.preferences.security" with a view and add "org.eclipse.equinox.security" as a dependency to this plug-in.

Change the code of your view to the following.

package de.vogella.preferences.security;

import org.eclipse.equinox.security.storage.ISecurePreferences;
import org.eclipse.equinox.security.storage.SecurePreferencesFactory;
import org.eclipse.equinox.security.storage.StorageException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;

public class View extends ViewPart {
  public void createPartControl(Composite parent) {
    Button buttonPut = new Button(parent, SWT.PUSH);
    buttonPut.setText("Save values");
    buttonPut.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
        ISecurePreferences preferences = SecurePreferencesFactory
            .getDefault();
        ISecurePreferences node = preferences.node("info");
        try {
          node.put("user", "vogella", true);
          node.put("password", "123", true);
        } catch (StorageException e1) {
          e1.printStackTrace();
        }
      }
    });
    Button buttonGet = new Button(parent, SWT.PUSH);
    buttonGet.setText("Get values");
    buttonGet.addSelectionListener(new SelectionAdapter() {
      @Override
      public void widgetSelected(SelectionEvent e) {
        ISecurePreferences preferences = SecurePreferencesFactory
            .getDefault();
        if (preferences.nodeExists("info")) {
          ISecurePreferences node = preferences.node("info");
          try {
            String user = node.get("user", "n/a");
            String password = node.get("password", "n/a");
            System.out.println(user);
            System.out.println(password);
          } catch (StorageException e1) {
            e1.printStackTrace();
          }
        }
      }
    });

  }

  
/** * Passing the focus request to the viewer's control. */
public void setFocus() { } }

8. Thank you

Please help me to support this article:

Flattr this

9. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.

10. Links and Literature

10.1. Source Code

Source Code of Examples

10.2. vogella Resources

vogella Training Android and Eclipse Training from the vogella team

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java and compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put everything you have under distributed version control system