vogella.de

Follow me on twitter
About Lars Vogel
Flattr this

Eclipse Preferences - Tutorial

Lars Vogel

Version 0.01

25.06.2009

Revision History
Revision 0.125.06.2009Lars Vogel
Separated from http://www.vogella.de/articles/RichClientPlatform/article.html

Eclipse Preferences

This article describes the usage of Eclipse preferences and preference pages.

Within this article Eclipse 3.5 will be used.


Table of Contents

1. Preferences
1.1. Overview
1.2. Preference Page
1.3. Pre-requisite for the examples
2. Using preferences
3. Preference Page
3.1. Project
3.2. Extension Point and Preference Page
3.3. Commands
4. Thank you
5. Questions and Discussion
6. Links and Literature
6.1. Source Code
6.2. vogella Resources

1. Preferences

1.1. Overview

Eclipse represents user settings via preferences. Eclipse preferences (org.osgi.service.prefs.Preferences) are very similar to java.utils.prefs.Preferences with some support of additional features. See Java Preferences for an overview of java.utils.prefs.Preferences.

Preferences are key / values pairs where the key is an arbitrary name for the preference. The value can be a boolean, string, int of another primitive type. Preferences are received and saved by get and put methods while the get methods also supply a default value in case the preferences is not yet set.

Eclipse Preferences use the Eclipse framework to save and retrieve data hence making is easy to re-use this.

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

  • 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 plugins and product definitions.

1.2. Preference Page

Preference Pages allow to modify / display the user / system settings. They have to implement the extension point org.eclipse.ui.preferencePages.

The class must implement IWorkbenchPreferencePage and must have a non-parameter constructor. The class PreferencePage or one of its subclasses can get extended, a good template is usually FieldEditor PreferencePage.

1.3. Pre-requisite for the examples

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 Eclipse RCP

for information on this. Eclipse Commands provides additional information around Eclipse Commands.

2. Using preferences

The following will create three commands. One of set the preference values. The next will display the values and the last will clear the preference values.

Create a new project "de.vogella.preferences.test" (see Eclipse RCP Tutorial for details). Use the "Hello RCP" as a template.

Create the following commands with the following default handler. Add these commands to the menu.

Table 1. Commands

CommandDefault HandlerDescription
de.vogella.preferences.test.setPreferencesde.vogella.preferences.test.handler.SetPreferencesSets the initial values of Preferences
de.vogella.preferences.test.deletePreferencesde.vogella.preferences.test.handler.DeletePreferencesDeletes the preference values
de.vogella.preferences.test.showPreferencesde.vogella.preferences.test.handler.ShowPreferencesDisplays the preference values

Create the following coding in the default handler.

			
package de.vogella.preferences.test.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;

public class SetPreferences extends AbstractHandler {

	public Object execute(ExecutionEvent event) throws ExecutionException {
		// This would be using instance scope
		// Preferences preferences = new InstanceScope()
		// .getNode("de.vogella.preferences.test");
		// This is using configuration scope
		Preferences preferences = new ConfigurationScope()
				.getNode("de.vogella.preferences.test");
		// This would be using default n scope
		// Preferences preferences = new DefaultScope()
		// .getNode(Application.PLUGIN_ID);
		Preferences sub1 = preferences.node("note1");
		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();
		}
		return null;
	}

}

		

			
package de.vogella.preferences.test.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;

public class DeletePreferences extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) {
		Preferences preferences = new ConfigurationScope()
				.getNode("de.vogella.preferences.test");
		Preferences sub1 = preferences.node("note1");
		Preferences sub2 = preferences.node("node2");
		// Delete the existing settings
		try {
			sub1.clear();
			sub2.clear();
		} catch (BackingStoreException e) {
			e.printStackTrace();
		}
		// Forces the application to save the preferences
		try {
			preferences.flush();
		} catch (BackingStoreException e) {
			e.printStackTrace();
		}
		return null;
	}
}

		

			
package de.vogella.preferences.test.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;
import org.osgi.service.prefs.Preferences;

public class ShowPreferences extends AbstractHandler {
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		Shell shell = HandlerUtil.getActiveWorkbenchWindowChecked(event)
				.getShell();
		Preferences preferences = new ConfigurationScope()
				.getNode("de.vogella.preferences.test");
		Preferences sub1 = preferences.node("note1");
		Preferences sub2 = preferences.node("node2");
		MessageDialog.openInformation(shell, "Info", sub1.get("h1", "default"));
		MessageDialog.openInformation(shell, "Info", sub1.get("h2", "default"));
		MessageDialog.openInformation(shell, "Info", sub2.get("h1", "default"));
		return null;
	}
}

		

Run and test your program. If you set the preferences and re-start the program the values should still be stored in the application.

3. Preference Page

3.1. Project

The following will create an example for preference pages.

Create a new RCP project "de.vogella.preferences.page" . Use the "Hello RCP" as a template.

Tip

The template which we are going to use requires an activator. Make sure you flag the "Generate an activator..." during the project creation.

3.2. Extension Point and Preference Page

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

Maintain the following code for your class "MyPreferencePage1".

				
package de.vogella.preferences.page.perferencepage;

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");
	}
}

			

3.3. Commands

To display the preference page you can re-use an existing Eclipse command.

Add the standard Eclipse command "org.eclipse.ui.window.preferences" to your menu. This will show the preference dialog. See Eclipse Commands for how to add a standard command to your menu.

Run the application. Now you can select your preference page via the menu.

Create a command "showPreferenceValues" with a default handler. Add this command also to your menu. Maintain the following coding for the default handler.

				
package de.vogella.preferences.page.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;

import de.vogella.preferences.page.Activator;

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");
		MessageDialog.openInformation(shell, "Info", myPrefBoolean.toString());
		// I assume you get the rest by yourself
		return null;
	}

}

			

This command demonstrates how to access preferences values from the preferencePage. Try to change values in the preference page, restart the application. The values should still be the changed ones.

4. Thank you

Thank you for practicing with this tutorial.

I maintain this tutorial in my private time. If you like the information please help me by using flattr or donating or by recommending this tutorial to other people.

Flattr this

5. 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.de Google Group . I have created a short list how to create good questions which might also help you. .

6. Links and Literature

6.1. Source Code

Source Code of Examples