dialogs and wizards

77
Dialogs and Wizards Cheng-Chia Chen Wu Kun-Tse

Upload: andie

Post on 13-Feb-2016

39 views

Category:

Documents


0 download

DESCRIPTION

Dialogs and Wizards. Cheng-Chia Chen Wu Kun-Tse. Outline. Introduction Extending the Preferences Dialog to Add Our Own Tool Options Using Property Pages to Remember Something Special About a Resource Using Wizards to Extend Workbench Resource Creation and Import/Export Support - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Dialogs and Wizards

Dialogs and Wizards

Cheng-Chia Chen Wu Kun-Tse

Page 2: Dialogs and Wizards

Outline Introduction Extending the Preferences Dialog to Add Our Own Tool

Options Using Property Pages to Remember Something Special

About a Resource Using Wizards to Extend Workbench Resource Creation

and Import/Export Support Summary Reference

Page 3: Dialogs and Wizards

Introduction We will discuss the various types of dialogs and wizards

that are available in Eclipse and how we can use and extend them as we develop our tools.

Dialogs and wizards define a framework for building complex interactions with the user.

The reusable dialogs provided will improve our tool development productivity, but the real value is the consistency of your tool with respect to the other tools that have been integrated with Eclipse.

Page 4: Dialogs and Wizards

Introduction (cont.) The workbench implements a generic preferences

architecture that allows plug-ins to store user preference values and

contribute a preference page to the workbench preferences dialog.

Property pages are very similar to preference pages. The primary difference is that property pages are associated with

a particular resource, while preferences are associated with the plug-in itself.

Wizards are used to guide the user through a sequenced set of tasks.

Page 5: Dialogs and Wizards

Preference API provides access to simple string-based key/v

alue pair storage in a flat structure. like Java Properties location: <ws>\.metadata\.plugins\<plugin>\pref_s

tore.ini Ex:

#Mon Mar 20 12:00:00 EST 2006 a.b.c=true a.b.d=a default value

Page 6: Dialogs and Wizards

Values associated with a preference current value

set by end-user default value

set by plug-in designer default-default value

set by Eclipse designer boolean false; numeric(int,long, float, double) 0 or 0.0 String ””.

Current value is stored only if it is different from its default value.

default values of all preferences for a plug-in can be specified in a file preference.ini in the plugin.

Page 7: Dialogs and Wizards

Preference store access. Plugin.getPluginPreferences()

need to call savePluginPreferences() to save the result when it is shutdown.

AbstractUIPlugin.getPreferenceStore() automatically saved when plguin stoped.

Page 8: Dialogs and Wizards

Preference access get current value :

getBoolean(String key): boolean getString(String) : String getXxxx(String) : xxxx

where xxxx is int, long, float or double. get default value:

getDefault<type>(key) : <type> where type is boolean, String, int, long, float and d

ouble.

Page 9: Dialogs and Wizards

set current value: setValue(Strign key, <type> value ) <type> is any of the above six types.

set default value: setDefault(key, <type> value ).

default = current ? isDefault(key) setToDefault(key) :

= set(key, getDefault(key) )

Page 10: Dialogs and Wizards

contains(key) : boolean get(key) != default-default value true.

defaultPropertyNames() : List<String> list of keys that have a non default-default default value.

propertyNames() : List<String> list of keys with current value != default value.

load(Stream); store(Stream) needsSaving(): boolean

dirty since last store().

Page 11: Dialogs and Wizards

Specify default values By a file called preferences.ini

at the root of your plugin. Programmatically (using extension).

<extension point=“org.eclipse.core.rutime.preferences”

<initializer class=“myplugin.id.MyPrefInitializer”> </>

Page 12: Dialogs and Wizards

public class MyPrefInitializer() extends AbstractPreferencesInitializer{

public class MyPrefInitializer() { Preferences p = MyPlugin.getDefault(). getPlu

ginPreferences(); p.setDefault( key1, v1) ; p.setDefault( key2, v2) ; …}

Page 13: Dialogs and Wizards

Listening for Preferences changing Implement a PropertyChangeListener

listener = new PropertyChangeListener() { public void PropertyChange(PropertyChangeEvent e ) { if( e.getProperty() .equals(key1 ) || … e.getProperty() .equals(keyK ) ) { updateMyView() ; }}

Registry with the Preferences: MyPlugin.getDefault.getPluginPreferences().addPropertyC

hangeListener( listener); Unregistry : …

.removePropertyChangeListener(listener).

Page 14: Dialogs and Wizards

Extending the Preferences Dialog to Add Our Own Tool Options Preference pages allow you to define settings that the

user can use to control tool behavior.

Page 15: Dialogs and Wizards

Steps to Create a Preference Page

1. Define a preference page extension.2. Implement a preference page.3. Define the preference page user interface.4. Establish default preference setting values.5. Add preference value logic to the preference

page.

Page 16: Dialogs and Wizards

Define a preference page extension Add an org.eclipse.ui.preferencePages extension definitio

n to plugin.xml.<extension point="org.eclipse.ui.preferencePages"> <page name="Soln: Basic Preference Page" class="com.ibm.lab.soln.dialogs.MyPrefPageBasic" id="com.ibm.lab.soln.dialogs.prefpage1"> </page> <page name="Soln: FieldEditor Preferences SubPage" category="com.ibm.lab.soln.dialogs.prefpage1" class="com.ibm.lab.soln.dialogs.MyPrefPageFieldEditor" id="com.ibm.lab.soln.dialogs.fieldPrefpage"> </page></extension>

Page 17: Dialogs and Wizards

Implement a preference page Creating a class implementing IWorkbenchPreferencePa

ge, or extends PreferencePage.

public class MyPrefPageBasic extends PreferencePage implements IWorkbenchPreferencePage { // The constructor. public MyPrefPageBasic([String title [ ImageDescriptor img]] ) { super( [title [,img]]) ; … } // Initializes the preference page by getting a local reference to // the Preferences object from the your Plugin. // Triggered only when the page is first accessed. public void init(IWorkbench workbench) { … }

// Implement the user interface for the preference page. protected Control createContents(Composite parent) { … }}

Page 18: Dialogs and Wizards

Implement a preference page (cont.) To implement support for modifying the preferences displ

ayed, you supply the logic for any displayed push buttons.

Methods to override to customize push button logic for preference pages:

performOK() should be overridden to to savepreference values. performApply() invokes performOK() by default.

call noDefaultAndApplyButton() in init() if do not want Apply and RestorDefault buttons.

Push Button Name Method

OK performOK()

Apply performApply()Restore Defaults performDefaults()Cancel performCancel()

Page 19: Dialogs and Wizards

Define the preference page user interface We will need to customize the createContents method to

add the widgets required in our user interface.protected Control createContents(Composite parent) { // Add layer to parent widget Composite composite = new Composite(parent, SWT.NONE); // Define laout rules for widget placement GridLayout compositeLayout = new GridLayout(); … composite.setLayout(compositeLayout);

Label labelN = new Label(group, SWT.NONE); labelN.setText( "Select the number of files to keep in the \nRecent Edits list:"); …

// return the widget used as the base for the user interface return composite;}

Page 20: Dialogs and Wizards

Preference Management in a Plug-in The preference settings are kept in a preference store that is obtain

ed from the associated plug-in and saved as part of the active workspace.

The tasks required to support storing preferences are: Get the preference store (PreferenceStore or Preferences object) from y

our plug-in. Establish any defaults for the preference settings to be supported Use this object to establish the init and modified contents of your prefere

nce page implementation Make sure the contents of the object are saved to disk when Eclipse shu

t down Eclipse provides two options for storing preference settings:

Use the AbstractUIPlugin API and a PreferenceStore object Use the Plugin API and a Preferences object

Page 21: Dialogs and Wizards

use PreferencesInitializer instead. If your plug-in class has extended AbstractUIPlugin, you

could re-implement either of the following methods establish preference-setting defaults. initializeDefaultPreferences(IPreferenceStore store)

initializeDefaultPluginPreferences()

Establish default preference setting values (deprecated)

protected void initializeDefaultPluginPreferences() { // Add an entry for each preference default value. // Do not send super. getPluginPreferences().setDefault( "text_field_key", "myTextDefaultValue");}

protected void initializeDefaultPreferences(IPreferenceStore store) { // Add an entry for each preference default value. store.setDefault("text_field_key", "myTextDefaultValue");}

Page 22: Dialogs and Wizards

Add preference value logic to the preference page There are several steps required to integrate our prefere

nce page with how the preference setting values will be stored. Finding the PreferenceStore or Preferences object for our plug-in Associating a preference page with a preference store Obtaining preference values for user interface(for Initialization) Getting defaults values (for restoreDefault) Saving modified preference setting values (for reuse nex time).

Page 23: Dialogs and Wizards

Finding the Preference Store or Preferences Object for Our Plug-in We can get a handle for the object used to store prefere

nces from our plug-in by using either of these methods:

The FieldEditorPreferencePage approach discussed later can only use a PreferenceStore object type.

IPreferenceStore ps = DialogPlugin.getDefault().getPreferenceStore();Preferences prefs = DialogPlugin.getDefault().getPluginPreferences();

Page 24: Dialogs and Wizards

Associating a Preference Page with a Preference Store If we get a PreferenceStore object from our plug-in, it can

be directly associated with our preference page using the setPreferenceStore method. This is best done in the init method as the page is activated.

The preference page hierarchy does not allow us to associate a Preferences object with the current preference page. We could choose to add an instance variable and set the value ourselves.

DialogsPlugin myPlugin = DialogsPlugin.getDefault();if (myPlugin instanceof AbstractUIPlugin) { AbstractUIPlugin uiPlugin = (AbstractUIPlugin) myPlugin; this.setPreferenceStore(uiPlugin.getPreferenceStore());}

Preferences pref = DialogsPlugin.getDefault().gtePluginPreferences();

Page 25: Dialogs and Wizards

Obtaining Preference Values for User Interface We need to show the current preference values in our

preference page so that the user can review them for possible modification.

The logic to get a String value for an identified preference setting for use in a UI control is shown below:

// PreferenceStore approachtextInfo.setText(getPreferenceStore.getString("text_field_key");

// Preferences approachtextInfo.setText( // or pref.getString(…) ; myPlugin.getDefault().getPluginPreferences().getString("text_field_key"));

Page 26: Dialogs and Wizards

Getting Default Values The Restore Defaults button in the preference page

allows the user to request that the settings be returned to their default values.

If we defined defaults in the plug-in, we can use this logic to obtain those defaults for display in the user interface:

// PreferenceStore approachtextInfo.setText( getPreferenceStore().getDefaultString( "text_field_key");

// Preferences approachtextInfo.setText( myPlugin.getDefault() .getPluginPreferences() .getDefaultString("text_field_key");

Page 27: Dialogs and Wizards

Saving Modified Preference Setting Values If the user selects Apply or OK button, you obtain the cu

rrent preference values from the user interface and modify the associated preference settings.

There is one set method, setValue, which takes keys of the preference setting and the value to be set.

// PreferenceStore approachgetPreferenceStore().setValue( "text_field_key", textInfo.getText());

// Preferences approachmyPlugin.getDefault().getPluginPreferences().setValue( "text_field_key", textInfo.getText());

Page 28: Dialogs and Wizards

Reacting to Preference Setting Changes If we need to know when a preference setting changes

so that we can dynamically react to the changes, we can ask to be notified by adding a property change listener.

// PreferenceStore approachDialogsPlugin .getDefault() .getPreferenceStore() .addPropertyChangeListener( new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { System.out.println(event.getProperty()); … }; });

Page 29: Dialogs and Wizards

Reacting to Preference Setting Changes (cont.)

// Preferences approachDialogsPlugin .getDefault() .getPluginPreferences() .addPropertyChangeListener( new Preferences.IPropertyChangeListener() { public void propertyChange(Preferences.PropertyChangeEvent event) { System.out.println(event.getProperty()); … }; });

Notes: Although Preferences.PropertyChangeEvent and jface.util.PropertyChangeEvent has the same signature and semantics, they are different classes. Preference.IPropertyChangeListener and o.e.jface.util.IPropertyChangeListener are the similar.

Page 30: Dialogs and Wizards

PropertyChangeEvent Extends j.u.EventObject Constructor

PropertyChangeEvent(Object source, String property, Object oldValue, Object newValue);

Readonly properties: source/*Preferences*/, property, oldValue, newVa

lueIPropertyChanegListener { void propertyChanged(PropertyChangeEvent)}

Page 31: Dialogs and Wizards

Building a Field Editor Preference Page Rather than extending the PreferencePage class above,

we can choose to build a field editor preference page. Steps:

Add a preference page extension. Implement a class that extends FieldEditorPreferencePage and i

mplements IWorkbenchPreferencePage to build on the field editor processing approach.

Associate a preference store with the preference page. Implement the creatFieldEditors method to create and add speci

alized field editors that define the user interface for the page. Example:

Eclipse Article: Simplifying Preference Pages with Field Editors

Page 32: Dialogs and Wizards

Field Editors provided FieldEditor

BooleanFieldEditor, ColorFieldEditor, FontFieldEditor, RadioGroupFieldEditor ScaleFieldEditor, ListEditor

PathEditor StringFieldEditor

IntegerFieldEditor StringButtonFieldEditor

FileFieldEditor DirectoryfieldEditor

Page 33: Dialogs and Wizards

Different Types of Field Editors

Page 34: Dialogs and Wizards
Page 35: Dialogs and Wizards

Using field editors with a FieldEditorPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage

class HTMLPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {

// ... }

Page 36: Dialogs and Wizards

instantiate and set a preference store for the preference page super(int) requires a layout const

GRID all fields share a single (one column) GRIDLayout FLAT each field handle its own layout.

public HTMLPreferencePage() { super(FieldEditorPreferencePage.GRID); // Set the preference store for the preference page. IPreferenceStore store = HTMLEditorPlugin.getDefault().

getPreferenceStore(); setPreferenceStore(store); }

Page 37: Dialogs and Wizards

The HTML Editor Preference Page

Page 38: Dialogs and Wizards

createFieldEditors() use addField(FieldEditor)protected void createFieldEditors() { // Initialize all field editors.

BooleanFieldEditor formatOnSave = new BooleanFieldEditor( IPreferenceConstants.FORMAT_PREFERENCE, //property

"&Format before saving", getFieldEditorParent()); addField(formatOnSave);

SpacerFieldEditor spacer1 = new SpacerFieldEditor( getFieldEditorParent()); addField(spacer1);

IntegerFieldEditor indentSpaces = new IntegerFieldEditor( IPreferenceConstants.INDENT_PREFERENCE,

"&Number of spaces to indent:", getFieldEditorParent()); indentSpaces.setValidRange(0, 10); addField(indentSpaces);

Page 39: Dialogs and Wizards

SpacerFieldEditor spacer2 = new SpacerFieldEditor( getFieldEditorParent()); addField(spacer2);

ColorFieldEditor commentColor = new ColorFieldEditor( IPreferenceConstants.COMMENT_COLOR_PREFERENCE, "C&omments:", getFieldEditorParent());

addField(commentColor);

ColorFieldEditor errorColor = … ; addField(errorColor); ColorFieldEditor validColor = …; addField(validColor);

FontFieldEditor font = new FontFieldEditor( IPreferenceConstants.FONT_PREFERENCE, "Edito&r font:", getFieldEditorParent()); addField(font);

SpacerFieldEditor spacer3 = new SpacerFieldEditor( getFieldEditorParent()); addField(spacer3);

FileFieldEditor webBrowser = new FileFieldEditor( IPreferenceConstants.BROWSER_PREFERENCE, "&Web browser:",

true, // enforceAbsolute getFieldEditorParent()); addField(webBrowser); }

Page 40: Dialogs and Wizards

Using field editors with a regular PreferencePage

Page 41: Dialogs and Wizards

Additional Works need to do In addition to creating the preference store

and instantiating field editors, you must write code to load preferences,

store preferences, and restore defaults. Without a FieldEditorPreferencePage, you

can still take advantage of a field editor's self-validation via the FieldEditor.isValid() method, but you must write the code that calls this method.

Page 42: Dialogs and Wizards

class ErrorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {

// ...

}

Page 43: Dialogs and Wizards

createContents(Composite)protected Control createContents(Composite parent) { Composite top = new Composite(parent, SWT.LEFT); // Sets the layout data for the top composite's // place in its parent's layout. top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // Sets the layout for the top composite's // children to populate. top.setLayout(new GridLayout()); errors = new

RadioGroupFieldEditor( IPreferenceConstants.ERRORS_PREFERENCE, // key

"Error conditions", 1, // #Column new String[][] { {"Don't show errors", // label IPreferenceConstants.NO_ERRORS }, // value

Page 44: Dialogs and Wizards

{“Show error if a closing tag is missing”, IPreferenceConstants.ERROR_FOR_MISSING_CLOSING_TAG } }, top /*container*/ , true // use group control );

errors.setPreferencePage(this); errors.setPreferenceStore(getPreferenceStore()); errors.load(); Label listLabel = new Label(top, SWT.NONE);listLabel.setText("Tags which do not require closing tags:");exemptTagsList = new List(top, SWT.BORDER);exemptTagsList.setItems( HTMLEditorPlugin.getDefault().getExemp

tTagsPreference()); // ...// The remainder of the code has been omitted for brevity. // ... return top; }

Page 45: Dialogs and Wizards

PerformDefaults(),performOK() needed for regular preference pageprotected void performDefaults() { errors.loadDefault(); exemptTagsList.setItems( HTMLEditorPlugin.getDefault().

getDefaultExemptTagsPreference() ); // getDefaultExemptTagsPreference() is a convenience // method which retrieves the default preference from // the preference store. super.performDefaults(); } public boolean performOk() { errors.store(); HTMLEditorPlugin.getDefault().

setExemptTagsPreference(exemptTagsList.getItems()); return super.performOk(); }

Page 46: Dialogs and Wizards

Using Property Pages to Remember Something Special About a Resource The role of a property page is to allow the user to see

and modify values associated with a specific object that supports the property dialog in Eclipse.

Page 47: Dialogs and Wizards

Steps to Create Property Page

1. Define a property page extension.2. Implement a property page.3. Define the property page user interface.4. Add resource property access logic.

Page 48: Dialogs and Wizards

Defining a Property Page Extension To add a property page, you create an org.eclipse.ui.pro

pertyPages extension definition in your plug-in manifest.

<extension point="org.eclipse.ui.propertyPages"> <page objectClass="org.eclipse.core.resources.IFile" adaptable="true" name="Soln: File Properties“ nameFilter=“*.java” class="com.ibm.lab.soln.dialogs.MyPropertyPage" id="com.ibm.lab.soln.dialogs.proppage1"> </page></extension>

Page 49: Dialogs and Wizards

Implementing a Property Page We define a property page by creating a class that imple

ments the IWorkbenchPropertyPage interface. The easiest way to accomplish this is to extend the PropertyPage class.

MyPropertyPage extends PropertyPage implements IWorkbenchPropertyPage {

// Creates the user interface for the property page. protected Control createContents(Composite parent) { … }

// Methods to override to customize push button logic for property pages performOK() { … }}

Page 50: Dialogs and Wizards

Defining the Property Page User Interface We customize the createContents() method to add the c

ontrols required in the user interface.protected Control createContents(Composite parent) { // Add layer to parent widget Composite composite = new Composite(parent, SWT.NONE); // Define laout rules for widget placement GridLayout compositeLayout = new GridLayout(); … composite.setLayout(compositeLayout);

Label labelB = new Label(group, SWT.NONE); labelB.setText("Select to disable Recent Edits list support:"); …

// return the widget used as the base for the user interface return composite;}

Page 51: Dialogs and Wizards

Adding Resource Property Access Logic The workspace API provides support for getting and setti

ng values for a specific resource. The IResource interface methods shown below support getting and setting both temporary (session) and permanent (persistent) values for any workspace resource.

setSessionProperty(QualifiedName key, Object value);getSessionProperty(QualifiedName key);setPersistentProperty(QualifiedName key, String value);getPersistentProperty(QualifiedName key);

Page 52: Dialogs and Wizards

Adding Resource Property Access Logic (cont.) We would use the “get” logic above to define the initial

state of the property page user interface.public static QualifiedName REDIT_PROPERTY_KEY = new QualifiedName("com.ibm.lab.soln.dialogs", "Recent_Edits");…public boolean getReditPropertyState() { IResource resource = (IResource) getElement(); try { String propValue = resource.getPersistentProperty( REDIT_PROPERTY_KEY); if ((propValue != null) && propValue.equals("True")) return true; else return false; } catch (CoreException e) { // Deal with exception. } return false;}

Page 53: Dialogs and Wizards

Adding Resource Property Access Logic (cont.) The “set” logic would translate the property to a String va

lue and be integrated as part of the performOK.public boolean performOk() { setReditPropertyState(reditFlag.getSelection()); return super.performOk();}public void setReditPropertyState(boolean value) { IResource resource = (IResource) getElement(); try { if (value) { resource.setPersistentProperty( REDIT_PROPERTY_KEY, "True"); } else { resource.setPersistentProperty( IDialogsIDs.REDIT_PROPERTY_KEY, "False"); } } catch (CoreException e) { } }

Page 54: Dialogs and Wizards

Using Wizards to Extend Workbench Resource Creation and Import/Export Support

Using the wizard framework, we can easily integrate wizards to create new resources or to import and export resources by defining an extension.

Page 55: Dialogs and Wizards

Steps to Create Wizard These steps are required to create a functioning wizard.

1. Define a wizard extension.2. Implement a wizard.3. Implement a wizard page.4. Define the wizard page user interface.5. Add the appropriate wizard processing logic.

These steps, and additional wizard customization and control topics, are discussed in the sections that follow.

Page 56: Dialogs and Wizards

Adding Wizards to the Workbench User Interface by Extension There are three extension points available that allow you

to add wizards to the Workbench. These extension points support the addition of entries to

the set of resource creation, import processing, and export processing wizards integrated into the Workbench user interface. org.eclipse.ui.newWizards org.eclipse.ui.importWizards org.eclipse.ui.exportWizards

Page 57: Dialogs and Wizards

Adding Wizards to the Workbench User Interface by Extension (cont.)

<extension id="dialogs.wizards“ name="Soln: Wizard Dialogs" point="org.eclipse.ui.newWizards"> <category name="Soln: My New Wizards" id="com.ibm.lab.soln.dialogs.wizard.new"> </category> <wizard name="Soln: My Basic Wizard" category="com.ibm.lab.soln.dialogs.wizard.new" class="com.ibm.lab.soln.dialogs.MyBasicWizard" id="com.ibm.lab.soln.dialogs.wizard.Basic"> <description> My Wizard does something simple. Later it will have more pages with control flow logic. </description> </wizard></extension>

Page 58: Dialogs and Wizards

Implementing a Wizard We build a wizard by creating a class that extends the

Wizard class and implements the appropriate interface (extension-point specific).

public class MyBasicWizard extends Wizard implements INewWizard { // The constructor. public MyBasicWizard() { }

// Subclasses must implement this IWizard method // to perform any special finish processing for their wizard. public boolean performFinish() { … }

// Initialize processing saves local workbench and // selection references and sets wizard title/image. public void init(IWorkbench workbench, IStructuredSelection selection) { … }}

Page 59: Dialogs and Wizards

Customizing the Wizard We can customize the user interface of a wizard by

adding to the init method.public void init(IWorkbench workbench, IStructuredSelection selection) { setWindowTitle("Customized Wizard Title"); setDefaultPageImageDescriptor(getImageDescriptor("eclipse.jpg")); …}

private ImageDescriptor getImageDescriptor(String relativePath) { String iconPath = "icons/"; try { DialogsPlugin plugin = DialogsPlugin.getDefault(); URL installURL = plugin.getDescriptor().getInstallURL(); URL url = new URL(installURL, iconPath + relativePath); return ImageDescriptor.createFromURL(url); } catch (MalformedURLException e) { // Should not happen return null; }}

Page 60: Dialogs and Wizards

Implementing a Wizard Page Implementing our own wizard page is as simple as creati

ng a class that extends the WizardPage class and overriding the createControl method to supply a user interface.

public void createControl(Composite parent) { Group optGroup = createGroup(parent, "Group Text"); createLabel(optGroup, "QRS: Basic Wizard Page One."); createText(optGroup, "Text Value");

// Add Page Control Button buttonC = new Button(optGroup, org.eclipse.swt.SWT.CHECK); buttonC.setText("Select to set pageComplete true"); ….

setControl(optGroup);}

Page 61: Dialogs and Wizards

Implementing a Wizard Page (cont.) We can populate the wizard with our pages by overriding

the addPages method.public void addPages() { // Add customized new file wizard page - set title and description attributes myNewPage = new MyNewFileWizardPage("New File", selection); addPage(myNewPage); myNewPage.setTitle("My New File Page Title"); myNewPage.setDescription("My New File Page Description");

// Add pages to the wizard page sequence // Constructor logic defined page title and addPage( new MyBasicWizardPage1("Page1", "My First Wizard Page", null, false)); addPage( new MyBasicWizardPage2("Page2", "My Second Wizard Page", null, false));}

Page 62: Dialogs and Wizards

Controlling Wizard Page Progression When more than one page is added to a wizard, the inhe

rited control logic determines if the Next button should be enabled.

We have the option of refining this logic by managing the pages status (setPageComplete method).

If a page is not complete, the user is not able to move forward.

The goals here are to ensure that our set of wizard pages collect the required information and that the information is correct.

Page 63: Dialogs and Wizards

Controlling Wizard Page Progression (cont.) If our addPages() added multiple pages, the following wo

uld happen. Progression through the pages would be supported using the Ne

xt button. The Next button would be enabled as long as there were more p

ages and the current page status was complete. The Finish button would be enabled as long as all pages had a p

age status of complete. If some user interaction or decision determines that anot

her page is required to support the ongoing wizard task, our implementation can override the getNextPage method in a wizard page or wizard to add dynamic support to the wizard page sequence.

Page 64: Dialogs and Wizards

Directly Opening a Wizard Dialog Wizards can also be used in places other than newWizar

d, importWizard and exportWizard. The wizard and wizard page definition process is the same. Definition of related extensions is no longer needed. But we need to wrap the wizard in a WizardDialog (which is a wiz

ard container) and open the dialog ourselves. An example of opening a wizard in a dialog as part of an

action that provides a reference to the selected resource is shown below.

Page 65: Dialogs and Wizards

Directly Opening a Wizard Dialog (cont.)

// Create the wizard StructureWizard wizard = new StructureWizard(); wizard.init(getWorkbench(), mySelection);

// Create the dialog to wrap the wizard WizardDialog dialog = new WizardDialog( getWorkbench().getActiveWorkbenchWindow().getShell(), wizard);

dialog.open();

Page 66: Dialogs and Wizards
Page 67: Dialogs and Wizards

Dialog Settings A dialog setting can store values for any kind of dialog, e

ven preference, property, and wizard dialogs. No change notification support.

Values saved in the file: dialog_settings.xml in plug-in’s state directory. in XML format partitioned into sections

The object IDialogSettings canbe got by: AbstractUIPlugin.getDialogSettings()

Page 68: Dialogs and Wizards

Dialog Logic Stored DataIDialogSettings dset = XXXXPlugin.getDefault() .getDialogSettings();String[] sList = { “a”, “b”, “c” };IDialogSettings dSection = dset.addNewSection( “MyValueSection”);dSection.put(“int”, 1);dSection.put(“double”, 2000000000);dSection.put(“long”, 3000000000);dSection.put(“float”, 4000000000);dSection.put(“trueFalse”, false);dSection.put(“string”, “myValue”);dSection.put(“stringArray”, sList);

<?xml version=“1.0” encoding=“UTF-8”?><section name=“Workbench”> <section name=“MyValueSection”> <item key=“trueFalse” value=“false”/> <item key=“string” value=“myValue”/> <item key=“double” value=“2.0E9”/> <item key=“long” value=“3000000000”/> <item key=“float” value=“4.0E8”/> <item key=“int” value=“1” /> <list key=“stringArray”> <item value=“a”/> <item value=“b”/> <item value=“c”/> </list> </section></section>

Saving Values in a Dialog Setting

Page 69: Dialogs and Wizards

Use case//Store valuesIDialogSettings d = XXXPlugin.getDefault().getDialogS

ettings();IDialogSection s = d.addNewSection(“SetionName”);String[] valueList = new String[]{“a”,”b”,”c”};s.put(“key”, valueList);//getValueIDialogSettings d = XXXPlugin.getDefault().getDialogS

ettings();IDialogSection s = d.getSection(“SetionName”);String[] valueList = s.getArray(“key”);

Page 70: Dialogs and Wizards

IDialogSettings API package org.eclipse.jface.dialogs

implementation: DialogSettings An interface to a storage mechanism for

making dialog settings persistent. The store manages a collection of key/value pairs. Keys must be strings and the values can be strings

or array of strings. Convenience API to convert primitive types to

strings.

Page 71: Dialogs and Wizards

get(String key ):String getArray(String) : String[] getXxx(String): xxx

xxx is boolean, int, long, float or double. getName() : String

return the name of the DialogSettings getSection(sectionName) getSections() :IDialogSettings[] load/save (Reader | String file )

load/save the file content into/from this settings. put(String key, xxx value)

xxx is boolean, int, long, float, double, String, or String[]. addNewSection(String sname) : DialogSettings

create a new section named sname and return it. addSection(DialogSettings sec)

add sec into this as a section.

Page 72: Dialogs and Wizards

o.e.j.dialog.DialogSettings a concrete implementation of IDialogSettings.

using a hash table and XML. can be read from and saved to a stream. All keys and values must be strings or array of

strings. Primitive types are converted to strings. Constructor:

DialogSettings(String name) fields/methods: same as IDialogSettings.

Page 73: Dialogs and Wizards

Example DialogSettings settings = new DialogSettings("root"); settings.put("Boolean1",true); settings.put("Long1",100); settings.put("Array1", new String[]{"aaaa1","bbbb1","cccc1"}); DialogSettings section = new DialogSettings("sectionName"); settings.addSection(section); section.put("Int2",200); section.put("Float2",1.1f); section.put("Array2", new String[]{"aaaa2","bbbb2","cccc2"}); settings.save("c:\\temp\\test\\dialog.xml");

Page 74: Dialogs and Wizards

Use dialog settings to initialize/ store control values in a dialog. protected Control createDialogArea(Composite parent){ IDialogSettings settings =

XXXPlugin.getDefault().getDialogSettings();checkbox = new Button(parent,SWT.CHECK);checkbox.setText("Generate sample section titles"); // initialize the checkbox according to the dialog settingscheckbox.setSelection( settings.getBoolean("GenSections") ); }

Page 75: Dialogs and Wizards

The value of the setting can be stored later when the ok button is pressed.

protected void okPressed() {IDialogSettings settings =

XXXPlugin.getDefault().getDialogSettings(); // store the value of the generate sections

checkbox settings.put("GenSections",

checkbox.getSelection() ); super.okPressed(); }

Page 76: Dialogs and Wizards

Summary This chapter reviewed how dialogs can be added, both

by extension and through direct invocation in custom tool logic.

This included the preference and property page contributions, as well as the specialized wizards for resource creation and import or export processing.

This knowledge will help us integrate our pages with the common preferences and properties dialogs that are part of Eclipse, add wizards to support any customized resource processing we may need, and add other dialogs to our tool as may be required.