In addition to injecting in specific elements from the context, it is also possible to acquire preferences from the Eclipse preference store. Recall that preferences are stored in a hierarchical node structure, with each node having an identifier (conventionally the plug-in name) and a number of key/value pairs. An annotation @Preference
allows these to be accessed easily.
String greeting
field to the Hello
part. To obtain a preference, annotate it with @Inject
and @Preference
as follows:@Inject @Preference(nodePath="com.packtpub.e4.application", value="greeting") private String greeting;
create()
method to use this greeting value as the initial value for the Hello label.@PostConstruct public void create(Composite parent) { label = new Label(parent, SWT.NONE); label.setText(greeting+" "+window.getLabel()+" "+random);
null
value for the greeting. IEclipsePreferences
object needs to be injected into the Hello
part. Add a new field called prefs
which is used to interact with the preferences store:@Inject @Preference(nodePath="com.packtpub.e4.application") private IEclipsePreferences prefs;
receiveEvent()
method created previously and set the value of the color as the greeting:@Inject @Optional public void receiveEvent( @UIEventTopic("rainbow/colour") String data) { label.setText(data); prefs.put("greeting", "I like " + data); prefs.sync(); }
@Preference
parameter on an @Optional
method:@Inject @Optional void setText(@Preference(nodePath="com.packtpub.e4.application", value="greeting") String text) { if (text != null && label != null && !label.isDisposed()) { // NB Run in UI thread! label.setText(text); } }
null
or being disposed.Acquiring preferences with E4 injection makes it trivial to obtain and set preference values. Using a single preference value is the easiest way to get individual values; however, if the preferences need to be mutated then a reference to the IEclipsePreferences
store is required.
If the user interface needs to react to changes in the preference, the preference value should be injected via a setter. When the preference value changes, the setter is invoked and it can update the UI.
Note that the preference value setter may be invoked on any thread; if the UI needs to be updated then this should be done via the UI thread. How to do this is covered in the next section.