Java/SWT JFace Eclipse/Wizard
Содержание
An address book, using a wizard to add a new entry
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
/**
* This class displays an address book, using a wizard to add a new entry
*/
public class AddressBook extends ApplicationWindow {
// The running instance of the application
private static AddressBook APP;
// The action that launches the wizard
AddEntryAction addEntryAction;
// The entries in the address book
java.util.List entries;
// The view
private TableViewer viewer;
/**
* AddressBook constructor
*/
public AddressBook() {
super(null);
// Store a reference to the running app
APP = this;
// Create the action and the entries collection
addEntryAction = new AddEntryAction();
entries = new LinkedList();
// Create the toolbar
addToolBar(SWT.NONE);
}
/**
* Gets a reference to the running application
*
* @return AddressBook
*/
public static AddressBook getApp() {
return APP;
}
/**
* Runs the application
*/
public void run() {
// Don"t return from open() until window closes
setBlockOnOpen(true);
// Open the main window
open();
// Dispose the display
Display.getCurrent().dispose();
}
/**
* Adds an entry
*
* @param entry
* the entry
*/
public void add(AddressEntry entry) {
entries.add(entry);
refresh();
}
/**
* Configures the shell
*
* @param shell
* the shell
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
// Set the title bar text
shell.setText("Address Book");
shell.setSize(600, 400);
}
/**
* Creates the main window"s contents
*
* @param parent
* the main window
* @return Control
*/
protected Control createContents(Composite parent) {
// Create the table viewer
viewer = new TableViewer(parent);
viewer.setContentProvider(new AddressBookContentProvider());
viewer.setLabelProvider(new AddressBookLabelProvider());
viewer.setInput(entries);
// Set up the table
Table table = viewer.getTable();
new TableColumn(table, SWT.LEFT).setText("First Name");
new TableColumn(table, SWT.LEFT).setText("Last Name");
new TableColumn(table, SWT.LEFT).setText("E-mail Address");
table.setHeaderVisible(true);
table.setLinesVisible(true);
// Update the column widths
refresh();
return table;
}
/**
* Creates the toolbar
*
* @param style
* the toolbar style
* @return ToolBarManager
*/
protected ToolBarManager createToolBarManager(int style) {
ToolBarManager tbm = new ToolBarManager(style);
// Add the action to launch the wizard
tbm.add(addEntryAction);
return tbm;
}
/**
* Updates the column widths
*/
private void refresh() {
viewer.refresh();
// Pack the columns
Table table = viewer.getTable();
for (int i = 0, n = table.getColumnCount(); i < n; i++) {
table.getColumn(i).pack();
}
}
/**
* The application entry point
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
new AddressBook().run();
}
}
/**
* This class contains an entry in the Address Book
*/
class AddressEntry {
private String lastName;
private String firstName;
private String email;
/**
* Gets the e-mail
*
* @return String
*/
public String getEmail() {
return email;
}
/**
* Sets the e-mail
*
* @param email
* The email to set.
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Gets the first name
*
* @return String
*/
public String getFirstName() {
return firstName;
}
/**
* Sets the first name
*
* @param firstName
* The firstName to set.
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Gets the last name
*
* @return String
*/
public String getLastName() {
return lastName;
}
/**
* Sets the last name
*
* @param lastName
* The lastName to set.
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
/**
* This class launches the add entry wizard
*/
class AddEntryAction extends Action {
/**
* AddEntryAction constructor
*/
public AddEntryAction() {
super("Add Entry", ImageDescriptor.createFromFile(AddEntryAction.class,
"/images/addEntry.gif"));
setToolTipText("Add Entry");
}
/**
* Runs the action
*/
public void run() {
WizardDialog dlg = new WizardDialog(AddressBook.getApp().getShell(),
new AddEntryWizard());
dlg.open();
}
}
/**
* This class represents the wizard for adding entries to the address book
*/
class AddEntryWizard extends Wizard {
// The pages in the wizard
private WelcomePage welcomePage;
private NamePage namePage;
private EmailPage emailPage;
/**
* AddEntryWizard constructor
*/
public AddEntryWizard() {
// Create the pages
welcomePage = new WelcomePage();
namePage = new NamePage();
emailPage = new EmailPage();
// Add the pages to the wizard
addPage(welcomePage);
addPage(namePage);
addPage(emailPage);
// Set the dialog window title
setWindowTitle("Address Book Entry Wizard");
}
/**
* Called when user clicks Finish Creates the entry in the address book
*/
public boolean performFinish() {
// Create the entry based on the inputs
AddressEntry entry = new AddressEntry();
entry.setFirstName(namePage.getFirstName());
entry.setLastName(namePage.getLastName());
entry.setEmail(emailPage.getEmail());
AddressBook.getApp().add(entry);
// Return true to exit wizard
return true;
}
}
/**
* This page collects the e-mail address
*/
class EmailPage extends WizardPage {
// The e-mail address
private String email = "";
/**
* EmailPage constructor
*/
public EmailPage() {
super("E-mail", "E-mail Address", ImageDescriptor.createFromFile(
EmailPage.class, "/images/email.gif"));
setDescription("Enter the e-mail address");
// Page isn"t complete until an e-mail address has been added
setPageComplete(false);
}
/**
* Creates the contents of the page
*
* @param parent
* the parent composite
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
// Create the label and text box to hold email address
new Label(composite, SWT.LEFT).setText("E-mail Address:");
final Text ea = new Text(composite, SWT.BORDER);
ea.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Add handler to update e-mail based on input
ea.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent event) {
email = ea.getText();
setPageComplete(email.length() > 0);
}
});
setControl(composite);
}
/**
* Gets the e-mail
*
* @return String
*/
public String getEmail() {
return email;
}
}
/**
* This page displays a welcome message
*/
class WelcomePage extends WizardPage {
/**
* WelcomePage constructor
*/
protected WelcomePage() {
super("Welcome", "Welcome", ImageDescriptor.createFromFile(
WelcomePage.class, "/images/welcome.gif"));
setDescription("Welcome to the Address Book Entry Wizard");
}
/**
* Creates the page contents
*
* @param parent
* the parent composite
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new FillLayout(SWT.VERTICAL));
new Label(composite, SWT.CENTER)
.setText("Welcome to the Address Book Entry Wizard!");
new Label(composite, SWT.LEFT)
.setText("This wizard guides you through creating an Address Book entry.");
new Label(composite, SWT.LEFT).setText("Click Next to continue.");
setControl(composite);
}
}
/**
* This page collects the first and last names
*/
class NamePage extends WizardPage {
// The first and last names
private String firstName = "";
private String lastName = "";
/**
* NamePage constructor
*/
public NamePage() {
super("Name", "Name", ImageDescriptor.createFromFile(NamePage.class,
"/images/name.gif"));
setDescription("Enter the first and last names");
setPageComplete(false);
}
/**
* Creates the page contents
*
* @param parent
* the parent composite
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
// Create the label and text field for first name
new Label(composite, SWT.LEFT).setText("First Name:");
final Text first = new Text(composite, SWT.BORDER);
first.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Create the label and text field for last name
new Label(composite, SWT.LEFT).setText("Last Name:");
final Text last = new Text(composite, SWT.BORDER);
last.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Add the handler to update the first name based on input
first.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent event) {
firstName = first.getText();
setPageComplete(firstName.length() > 0 && lastName.length() > 0);
}
});
// Add the handler to update the last name based on input
last.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent event) {
lastName = last.getText();
setPageComplete(firstName.length() > 0 && lastName.length() > 0);
}
});
setControl(composite);
}
/**
* Gets the first name
*
* @return String
*/
public String getFirstName() {
return firstName;
}
/**
* Gets the last name
*
* @return String
*/
public String getLastName() {
return lastName;
}
}
/**
* This class provides the content for the AddressBook application
*/
class AddressBookContentProvider implements IStructuredContentProvider {
/**
* Gets the elements
*
* @param inputElement
* the List of elements
* @return Object[]
*/
public Object[] getElements(Object inputElement) {
return ((List) inputElement).toArray();
}
/**
* Disposes any resources
*/
public void dispose() {
// Do nothing
}
/**
* Called when the input changes
*
* @param viewer
* the viewer
* @param oldInput
* the old input
* @param newInput
* the new input
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// Do nothing
}
}
/**
* This class provides the labels for the Address Book application
*/
class AddressBookLabelProvider implements ITableLabelProvider {
/**
* Gets the image for the column
*
* @param element
* the element
* @param columnIndex
* the column index
*/
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
/**
* Gets the text for the column
*
* @param element
* the element
* @param columnIndex
* the column index
*/
public String getColumnText(Object element, int columnIndex) {
AddressEntry ae = (AddressEntry) element;
switch (columnIndex) {
case 0:
return ae.getFirstName();
case 1:
return ae.getLastName();
case 2:
return ae.getEmail();
}
return "";
}
/**
* Adds a listener
*
* @param listener
* the listener
*/
public void addListener(ILabelProviderListener listener) {
// Do nothing
}
/**
* Disposes any resources
*/
public void dispose() {
// Do nothing
}
/**
* Returns true if changing the property for the element would change the
* label
*
* @param element
* the element
* @param property
* the property
*/
public boolean isLabelProperty(Object element, String property) {
return false;
}
/**
* Removes a listener
*
* @param listener
* the listener
*/
public void removeListener(ILabelProviderListener listener) {
// Do nothing
}
}
A survey using a wizard
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* This class displays a survey using a wizard
*/
public class Survey {
/**
* Runs the application
*/
public void run() {
Display display = new Display();
// Create the parent shell for the dialog, but don"t show it
Shell shell = new Shell(display);
// Create the dialog
WizardDialog dlg = new WizardDialog(shell, new SurveyWizard());
dlg.open();
// Dispose the display
display.dispose();
}
/**
* The application entry point
*
* @param args
* the command line arguments
*/
public static void main(String[] args) {
new Survey().run();
}
}
/**
* This class shows a satisfaction survey
*/
class SurveyWizard extends Wizard {
public SurveyWizard() {
// Add the pages
addPage(new ComplaintsPage());
addPage(new MoreInformationPage());
addPage(new ThanksPage());
}
/**
* Called when user clicks Finish
*
* @return boolean
*/
public boolean performFinish() {
// Dismiss the wizard
return true;
}
}
/**
* This class determines if the user has complaints. If not, it jumps to the last
* page of the wizard
*/
class ComplaintsPage extends WizardPage {
private Button yes;
private Button no;
/**
* ComplaintsPage constructor
*/
public ComplaintsPage() {
super("Complaints");
}
/**
* Creates the page controls
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, true));
new Label(composite, SWT.LEFT).setText("Do you have complaints?");
Composite yesNo = new Composite(composite, SWT.NONE);
yesNo.setLayout(new FillLayout(SWT.VERTICAL));
yes = new Button(yesNo, SWT.RADIO);
yes.setText("Yes");
no = new Button(yesNo, SWT.RADIO);
no.setText("No");
setControl(composite);
}
public IWizardPage getNextPage() {
// If they have complaints, go to the normal next page
if (yes.getSelection()) { return super.getNextPage(); }
// No complaints? Short-circuit the rest of the pages
return getWizard().getPage("Thanks");
}
}
/**
* This page gathers more information about the complaint
*/
class MoreInformationPage extends WizardPage {
/**
* MoreInformationPage constructor
*/
public MoreInformationPage() {
super("More Info");
}
/**
* Creates the controls for this page
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(1, false));
new Label(composite, SWT.LEFT).setText("Please enter your complaints");
Text text = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
text.setLayoutData(new GridData(GridData.FILL_BOTH));
setControl(composite);
}
}
/**
* This page thanks the user for taking the survey
*/
class ThanksPage extends WizardPage {
/**
* ThanksPage constructor
*/
public ThanksPage() {
super("Thanks");
}
/**
* Creates the controls for this page
*/
public void createControl(Composite parent) {
Label label = new Label(parent, SWT.CENTER);
label.setText("Thanks!");
setControl(label);
}
}
SWT Wizard Composite
/*
SWT/JFace in Action
GUI Design with Eclipse 3.0
Matthew Scarpino, Stephen Holder, Stanford Ng, and Laurent Mihalkovic
ISBN: 1932394273
Publisher: Manning
*/
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class Ch11WizardComposite extends Composite {
public Ch11WizardComposite(Composite parent) {
super(parent, SWT.NONE);
buildControls();
}
protected void buildControls() {
final Composite parent = this;
FillLayout layout = new FillLayout();
parent.setLayout(layout);
Button dialogBtn = new Button(parent, SWT.PUSH);
dialogBtn.setText("Wizard Dialog...");
dialogBtn.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
WizardDialog dialog = new WizardDialog(parent.getShell(),
new ProjectWizard());
dialog.open();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
}
class ProjectWizard extends Wizard {
public ProjectWizard() {
super();
}
public void addPages() {
addPage(new DirectoryPage());
addPage(new ChooseDirectoryPage());
addPage(new SummaryPage());
}
public boolean performFinish() {
DirectoryPage dirPage = getDirectoryPage();
if (dirPage.useDefaultDirectory()) {
System.out.println("Using default directory");
} else {
ChooseDirectoryPage choosePage = getChoosePage();
System.out.println("Using directory: " + choosePage.getDirectory());
}
return true;
}
private ChooseDirectoryPage getChoosePage() {
return (ChooseDirectoryPage) getPage(ChooseDirectoryPage.PAGE_NAME);
}
private DirectoryPage getDirectoryPage() {
return (DirectoryPage) getPage(DirectoryPage.PAGE_NAME);
}
public boolean performCancel() {
System.out.println("Perform Cancel called");
return true;
}
public IWizardPage getNextPage(IWizardPage page) {
if (page instanceof DirectoryPage) {
DirectoryPage dirPage = (DirectoryPage) page;
if (dirPage.useDefaultDirectory()) {
SummaryPage summaryPage = (SummaryPage) getPage(SummaryPage.PAGE_NAME);
summaryPage.updateText("Using default directory");
return summaryPage;
}
}
IWizardPage nextPage = super.getNextPage(page);
if (nextPage instanceof SummaryPage) {
SummaryPage summary = (SummaryPage) nextPage;
DirectoryPage dirPage = getDirectoryPage();
summary
.updateText(dirPage.useDefaultDirectory() ? "Using default directory"
: "Using directory:"
+ getChoosePage().getDirectory());
}
return nextPage;
}
}
class SummaryPage extends WizardPage {
public static final String PAGE_NAME = "Summary";
private Label textLabel;
public SummaryPage() {
super(PAGE_NAME, "Summary Page", null);
}
public void createControl(Composite parent) {
Composite topLevel = new Composite(parent, SWT.NONE);
topLevel.setLayout(new FillLayout());
textLabel = new Label(topLevel, SWT.CENTER);
textLabel.setText("");
setControl(topLevel);
setPageComplete(true);
}
public void updateText(String newText) {
textLabel.setText(newText);
}
}
class DirectoryPage extends WizardPage {
public static final String PAGE_NAME = "Directory";
private Button button;
public DirectoryPage() {
super(PAGE_NAME, "Directory Page", null);
}
public void createControl(Composite parent) {
Composite topLevel = new Composite(parent, SWT.NONE);
topLevel.setLayout(new GridLayout(2, false));
Label l = new Label(topLevel, SWT.CENTER);
l.setText("Use default directory?");
button = new Button(topLevel, SWT.CHECK);
setControl(topLevel);
setPageComplete(true);
}
public boolean useDefaultDirectory() {
return button.getSelection();
}
}
class ChooseDirectoryPage extends WizardPage {
public static final String PAGE_NAME = "Choose Directory";
private Text text;
public ChooseDirectoryPage() {
super(PAGE_NAME, "Choose Directory Page", null);
}
public void createControl(Composite parent) {
Composite topLevel = new Composite(parent, SWT.NONE);
topLevel.setLayout(new GridLayout(2, false));
Label l = new Label(topLevel, SWT.CENTER);
l.setText("Enter the directory to use:");
text = new Text(topLevel, SWT.SINGLE);
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
setControl(topLevel);
setPageComplete(true);
}
public String getDirectory() {
return text.getText();
}
}
Wizard Demo
/******************************************************************************
* All Right Reserved.
* Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-5-20 16:38:39 by JACK
* $Id$
*
*****************************************************************************/
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.jface.wizard.WizardDialog;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.jface.wizard.WizardPage;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.Wizard;
// The data model.
class ReservationData {
Date arrivalDate;
Date departureDate;
int roomType;
String customerName;
String customerPhone;
String customerEmail;
String customerAddress;
int creditCardType;
String creditCardNumber;
String creditCardExpiration;
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("* HOTEL ROOM RESERVATION DETAILS *\n");
sb.append("Arrival date:\t" + arrivalDate.toString() + "\n");
sb.append("Departure date:\t" + departureDate.toString() + "\n");
sb.append("Room type:\t" + roomType + "\n");
sb.append("Customer name:\t" + customerName + "\n");
sb.append("Customer email:\t" + customerEmail + "\n");
sb.append("Credit card no.:\t" + creditCardNumber + "\n");
return sb.toString();
}
}
/**
*
*/
class ReservationWizard extends Wizard {
static final String DIALOG_SETTING_FILE = "userInfo.xml";
static final String KEY_CUSTOMER_NAME = "customer-name";
static final String KEY_CUSTOMER_EMAIL = "customer-email";
static final String KEY_CUSTOMER_PHONE = "customer-phone";
static final String KEY_CUSTOMER_ADDRESS = "customer-address";
// the model object.
ReservationData data = new ReservationData();
public ReservationWizard() {
setWindowTitle("Hotel room reservation wizard");
setNeedsProgressMonitor(true);
setDefaultPageImageDescriptor(ImageDescriptor.createFromFile(null, "icons/hotel.gif"));
DialogSettings dialogSettings = new DialogSettings("userInfo");
try {
// loads existing settings if any.
dialogSettings.load(DIALOG_SETTING_FILE);
} catch (IOException e) {
e.printStackTrace();
}
setDialogSettings(dialogSettings);
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.IWizard#addPages()
*/
public void addPages() {
addPage(new FrontPage());
addPage(new CustomerInfoPage());
addPage(new PaymentInfoPage());
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.IWizard#performFinish()
*/
public boolean performFinish() {
if(getDialogSettings() != null) {
getDialogSettings().put(KEY_CUSTOMER_NAME, data.customerName);
getDialogSettings().put(KEY_CUSTOMER_PHONE, data.customerPhone);
getDialogSettings().put(KEY_CUSTOMER_EMAIL, data.customerEmail);
getDialogSettings().put(KEY_CUSTOMER_ADDRESS, data.customerAddress);
try {
// Saves the dialog settings into the specified file.
getDialogSettings().save(DIALOG_SETTING_FILE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
try {
// puts the data into a database ...
getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
monitor.beginTask("Store data", 100);
monitor.worked(40);
// store data here ...
System.out.println(data);
Thread.sleep(2000);
monitor.done();
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.IWizard#performCancel()
*/
public boolean performCancel() {
boolean ans = MessageDialog.openConfirm(getShell(), "Confirmation", "Are you sure to cancel the task?");
if(ans)
return true;
else
return false;
}
}
/******************************************************************************
* All Right Reserved.
* Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-5-20 20:08:05 by JACK
* $Id$
*
*****************************************************************************/
/**
*
*/
class PaymentInfoPage extends WizardPage {
Combo comboCreditCardTypes;
Text textCreditCardNumber;
Text textCreditCardExpiration;
public PaymentInfoPage() {
super("PaymentInfo");
setTitle("Payment information");
setDescription("Please enter your credit card details");
setPageComplete(false);
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.ruposite)
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout(2, false));
new Label(composite, SWT.NULL).setText("Credit card type: ");
comboCreditCardTypes = new Combo(composite, SWT.READ_ONLY | SWT.BORDER);
comboCreditCardTypes.add("American Express");
comboCreditCardTypes.add("Master Card");
comboCreditCardTypes.add("Visa");
comboCreditCardTypes.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
new Label(composite, SWT.NULL).setText("Credit card number: ");
textCreditCardNumber = new Text(composite, SWT.SINGLE | SWT.BORDER);
textCreditCardNumber.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
new Label(composite, SWT.NULL).setText("Expiration (MM/YY)");
textCreditCardExpiration = new Text(composite, SWT.SINGLE | SWT.BORDER);
textCreditCardExpiration.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
comboCreditCardTypes.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
((ReservationWizard)getWizard()).data.creditCardType = comboCreditCardTypes.getSelectionIndex();
if(((ReservationWizard)getWizard()).data.creditCardNumber != null &&
((ReservationWizard)getWizard()).data.creditCardExpiration != null)
setPageComplete(true);
else
setPageComplete(false);
}
});
textCreditCardNumber.addListener(SWT.Modify, new Listener() {
public void handleEvent(Event event) {
((ReservationWizard)getWizard()).data.creditCardNumber = textCreditCardNumber.getText();
if(((ReservationWizard)getWizard()).data.creditCardNumber != null &&
((ReservationWizard)getWizard()).data.creditCardExpiration != null)
setPageComplete(true);
else
setPageComplete(false);
}
});
textCreditCardExpiration.addListener(SWT.Modify, new Listener() {
public void handleEvent(Event event) {
String text = textCreditCardExpiration.getText().trim();
if(text.length() == 5 && text.charAt(2) == "/") {
((ReservationWizard)getWizard()).data.creditCardExpiration = text;
setErrorMessage(null);
}else{
((ReservationWizard)getWizard()).data.creditCardExpiration = null;
setErrorMessage("Invalid expiration date: " + text);
}
if(((ReservationWizard)getWizard()).data.creditCardNumber != null &&
((ReservationWizard)getWizard()).data.creditCardExpiration != null)
setPageComplete(true);
else
setPageComplete(false);
}
});
setControl(composite);
}
}
/*******************************************************************************
* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-5-20 19:18:40 by JACK $Id$
*
******************************************************************************/
/**
*
*/
class CustomerInfoPage extends WizardPage {
Text textName;
Text textPhone;
Text textEmail;
Text textAddress;
public CustomerInfoPage() {
super("CustomerInfo");
setTitle("Customer Information");
setPageComplete(false);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.ruposite)
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout(2, false));
new Label(composite, SWT.NULL).setText("Full name: ");
textName = new Text(composite, SWT.SINGLE | SWT.BORDER);
textName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
new Label(composite, SWT.NULL).setText("Phone Number: ");
textPhone = new Text(composite, SWT.SINGLE | SWT.BORDER);
textPhone.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
new Label(composite, SWT.NULL).setText("Email address: ");
textEmail = new Text(composite, SWT.SINGLE | SWT.BORDER);
textEmail.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
new Label(composite, SWT.NULL).setText("Address: ");
textAddress = new Text(composite, SWT.MULTI | SWT.BORDER);
textAddress.setText("\r\n\r\n\r\n");
textAddress.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == null || !(event.widget instanceof Text))
return;
String string = ((Text) event.widget).getText();
if (event.widget == textName) {
((ReservationWizard) getWizard()).data.customerName =
string;
} else if (event.widget == textPhone) {
((ReservationWizard) getWizard()).data.customerPhone =
string;
} else if (event.widget == textEmail) {
if (string.indexOf("@") < 0) {
setErrorMessage("Invalid email address: " + string);
((ReservationWizard) getWizard()).data.customerEmail =
null;
} else {
setErrorMessage(null);
((ReservationWizard) getWizard()).data.customerEmail =
string;
}
} else if (event.widget == textAddress) {
((ReservationWizard) getWizard()).data.customerAddress =
string;
}
ReservationData data = ((ReservationWizard) getWizard()).data;
if (data.customerName != null
&& data.customerPhone != null
&& data.customerEmail != null
&& data.customerAddress != null) {
setPageComplete(true);
} else {
setPageComplete(false);
}
}
};
textName.addListener(SWT.Modify, listener);
textPhone.addListener(SWT.Modify, listener);
textEmail.addListener(SWT.Modify, listener);
textAddress.addListener(SWT.Modify, listener);
if (getDialogSettings() != null && validDialogSettings()) {
textName.setText(
getDialogSettings().get(
ReservationWizard.KEY_CUSTOMER_NAME));
textPhone.setText(
getDialogSettings().get(
ReservationWizard.KEY_CUSTOMER_PHONE));
textEmail.setText(
getDialogSettings().get(
ReservationWizard.KEY_CUSTOMER_EMAIL));
textAddress.setText(
getDialogSettings().get(
ReservationWizard.KEY_CUSTOMER_ADDRESS));
}
setControl(composite);
}
private boolean validDialogSettings() {
if (getDialogSettings().get(ReservationWizard.KEY_CUSTOMER_NAME)
== null
|| getDialogSettings().get(ReservationWizard.KEY_CUSTOMER_ADDRESS)
== null
|| getDialogSettings().get(ReservationWizard.KEY_CUSTOMER_EMAIL)
== null
|| getDialogSettings().get(ReservationWizard.KEY_CUSTOMER_PHONE)
== null)
return false;
return true;
}
}
/******************************************************************************
* All Right Reserved.
* Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-5-20 15:09:10 by JACK
* $Id$
*
*****************************************************************************/
/**
*
*/
class FrontPage extends WizardPage {
Combo comboRoomTypes;
Combo comboArrivalYear;
Combo comboArrivalMonth;
Combo comboArrivalDay;
Combo comboDepartureYear;
Combo comboDepartureMonth;
Combo comboDepartureDay;
FrontPage() {
super("FrontPage");
setTitle("Your reservation information");
setDescription("Select the type of room and your arrival date & departure date");
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.ruposite)
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NULL);
GridLayout gridLayout = new GridLayout(2, false);
composite.setLayout(gridLayout);
new Label(composite, SWT.NULL).setText("Arrival date: ");
Composite compositeArrival = new Composite(composite, SWT.NULL);
compositeArrival.setLayout(new RowLayout());
String[] months = new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
Calendar calendar = new GregorianCalendar(); // today.
((ReservationWizard)getWizard()).data.arrivalDate = calendar.getTime();
comboArrivalMonth = new Combo(compositeArrival, SWT.BORDER | SWT.READ_ONLY);
for(int i=0; i<months.length; i++)
comboArrivalMonth.add(months[i]);
comboArrivalMonth.select(calendar.get(Calendar.MONTH));
comboArrivalDay = new Combo(compositeArrival, SWT.BORDER | SWT.READ_ONLY);
for(int i=0; i<31; i++)
comboArrivalDay.add("" + (i+1));
comboArrivalDay.select(calendar.get(Calendar.DAY_OF_MONTH)-1);
comboArrivalYear = new Combo(compositeArrival, SWT.BORDER | SWT.READ_ONLY);
for(int i=2004; i<2010; i++)
comboArrivalYear.add("" + i);
comboArrivalYear.select(calendar.get(Calendar.YEAR)-2004);
calendar.add(Calendar.DATE, 1); // tomorrow.
((ReservationWizard)getWizard()).data.departureDate = calendar.getTime();
new Label(composite, SWT.NULL).setText("Departure date: ");
Composite compositeDeparture = new Composite(composite, SWT.NULL | SWT.READ_ONLY);
compositeDeparture.setLayout(new RowLayout());
comboDepartureMonth = new Combo(compositeDeparture, SWT.NULL | SWT.READ_ONLY);
for(int i=0; i<months.length; i++)
comboDepartureMonth.add(months[i]);
comboDepartureMonth.select(calendar.get(Calendar.MONTH));
comboDepartureDay = new Combo(compositeDeparture, SWT.NULL | SWT.READ_ONLY);
for(int i=0; i<31; i++)
comboDepartureDay.add("" + (i+1));
comboDepartureDay.select(calendar.get(Calendar.DAY_OF_MONTH)-1);
comboDepartureYear = new Combo(compositeDeparture, SWT.NULL | SWT.READ_ONLY);
for(int i=2004; i<2010; i++)
comboDepartureYear.add("" + i);
comboDepartureYear.select(calendar.get(Calendar.YEAR)-2004);
// draws a line.
Label line = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 2;
line.setLayoutData(gridData);
new Label(composite, SWT.NULL).setText("Room type: ");
comboRoomTypes = new Combo(composite, SWT.BORDER | SWT.READ_ONLY);
comboRoomTypes.add("Standard room (rate: $198)");
comboRoomTypes.add("Deluxe room (rate: $298)");
comboRoomTypes.select(0);
Listener selectionListener = new Listener() {
public void handleEvent(Event event) {
int arrivalDay = comboArrivalDay.getSelectionIndex() + 1;
int arrivalMonth = comboArrivalMonth.getSelectionIndex();
int arrivalYear = comboArrivalYear.getSelectionIndex() + 2004;
int departureDay = comboDepartureDay.getSelectionIndex() + 1;
int departureMonth = comboDepartureMonth.getSelectionIndex();
int departureYear = comboDepartureYear.getSelectionIndex() + 2004;
setDates(arrivalDay, arrivalMonth, arrivalYear,
departureDay, departureMonth, departureYear);
}
};
comboArrivalDay.addListener(SWT.Selection, selectionListener);
comboArrivalMonth.addListener(SWT.Selection, selectionListener);
comboArrivalYear.addListener(SWT.Selection, selectionListener);
comboDepartureDay.addListener(SWT.Selection, selectionListener);
comboDepartureMonth.addListener(SWT.Selection, selectionListener);
comboDepartureYear.addListener(SWT.Selection, selectionListener);
comboRoomTypes.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
((ReservationWizard)getWizard()).data.roomType = comboRoomTypes.getSelectionIndex();
}
});
setControl(composite);
}
// validates the dates and update the model data object.
private void setDates(int arrivalDay, int arrivalMonth, int arrivalYear, int departureDay, int departureMonth, int departureYear) {
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.DAY_OF_MONTH, arrivalDay);
calendar.set(Calendar.MONTH, arrivalMonth);
calendar.set(Calendar.YEAR, arrivalYear);
Date arrivalDate = calendar.getTime();
calendar.set(Calendar.DAY_OF_MONTH, departureDay);
calendar.set(Calendar.MONTH, departureMonth);
calendar.set(Calendar.YEAR, departureYear);
Date departureDate = calendar.getTime();
System.out.println(arrivalDate + " - " + departureDate);
if(! arrivalDate.before(departureDate)) { // arrival date is before dep. date.
setErrorMessage("The arrival date is not before the departure date");
setPageComplete(false);
}else{
setErrorMessage(null); // clear error message.
setPageComplete(true);
((ReservationWizard)getWizard()).data.arrivalDate = arrivalDate;
((ReservationWizard)getWizard()).data.departureDate = departureDate;
}
}
}
/*******************************************************************************
* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-5-20 14:41:48 by JACK $Id$
*
******************************************************************************/
public class HotelReservation extends ApplicationWindow {
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.ruposite)
*/
protected Control createContents(Composite parent) {
Button button = new Button(parent, SWT.PUSH);
button.setText("Make a reservation");
button.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
ReservationWizard wizard = new ReservationWizard();
WizardDialog dialog = new WizardDialog(getShell(), wizard);
dialog.setBlockOnOpen(true);
int returnCode = dialog.open();
if(returnCode == Dialog.OK)
System.out.println(wizard.data);
else
System.out.println("Cancelled");
}
});
return button;
}
/**
* @param parentShell
*/
public HotelReservation(Shell parentShell) {
super(parentShell);
}
public static void main(String[] args) {
HotelReservation reservation = new HotelReservation(null);
reservation.setBlockOnOpen(true);
reservation.open();
}
}