Over a million developers have joined DZone.

Discover Eclipse's JFace Dialogs

· Java Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

The JFace framework of Eclipse provides many standard and useful dialogs and a framework to build custom dialogs and wizards. When the standard dialogs seems to be too simple for your plugin or RCP developement, one can extend the standard dialogs to suit their own needs. The aim of this article is to provide example oriented approach to dialogs and see in depth of all frequently used dialogs. I am hoping to have this article as the point of reference for many developers to get an overview of Dialogs.

Dialogs are modal UI components which would do some user interaction tasks. Traditionally Dialogs are used to enter a simple input, to select a choice from a list, to select multiple nodes from a tree, to inform about a success/failure from an operation, to input confirmations from the user, and so on.

Eclipse provides standard dialogs from two different frameworks, SWT provides very basic dialogs like FontDialog, ColorDialog, DirectoryDialog, FileDialog and FontDialog. These SWT dialogs are coming out of the SWT as they are very basic and has close connection to the OS. All these Dialogs are available from org.eclipse.swt.widgets package from the org.eclipse.swt.<platform>.jar.

JFace provides a variety of Dialogs for the implementors to extend or to use them directly. Its interesting to look into variety of dialogs provided by JFace and i would leave the usage to your imagination and context. Rest of this article is mostly code, screen shots and less of textual description. I tried to keep the short, sweet and simple.

FileDialog

This is a SWT Dialog but worth mentioning under the general concept of the Dialogs.

"Instances of this class allow the user to navigate the file system and select or enter a file name. Note: Only one of the styles SAVE and OPEN may be specified. IMPORTANT: This class is intended to be subclassed <em>only</em> within the SWT implementation."

FileDialog fsd = new FileDialog(shell);
fsd.setFilterExtensions(new String[] {"*.jpg"});
fsd.setText("Select My JPG Files...");
fsd.open();

 

File Dialog

 

Information Dialogs

These dialogs are used to inform user about some event and take some necessary action. There are different Dialogs under this category.

ErrorDialog

 "A dialog to display one or more errors to the user, as contained in an IStatus object. If an error contains additional detailed information then a Details button is automatically supplied, which shows or hides an error details viewer when pressed by the user."

ErrorDialog.openError(shell, "This is Error Title", "This is Error Message", status);

 

Error Dialog

 

MessageDialog

"A dialog for showing messages to the user. This concrete dialog class can be instantiated as is, or further subclassed as required."

MessageDialog.openInformation(shell, "Message Dialog Information", "This is some random Message");

 

Information Dialog

 

MessageDialog.openQuestion(shell, "This is a Tricky Question", "Do you know whats 2 + 3 = ?");
Question Dialog

 

InputDialog

This Dialog is used for a very general paradigm to process some input from the user. Generally its not recommended to use this for input of complex data and for large number of input fields.

	    final InputDialog id = new InputDialog(shell, "Enter Your Name", "Your name will be entered in Nobel Prize List.", "<Your Name>", new IInputValidator() {
public String isValid(String newText) {
if (newText.contains("x")) {
return "Your name can not have \"x\" character.";
}
return null;
}
});

id.open();

 

InputDialog

 

PrinterDialog

 "Instances of this class allow the user to select a printer and various print-related parameters prior to starting a print job. IMPORTANT: This class is intended to be subclassed only within the SWT implementation."

	    PrintDialog pd = new PrintDialog(shell);
pd.open();

 

Print Dialog

 

ProgressMonitorDialog

 This is a very important Dialog component most of the applications would use. This Dialog is used to represent any time consuming task or to provide a long running workspace task to the user. Proper care must be taken to show accurate information of progress information to the user.

	    ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
pmd.setCancelable(true);
pmd.create();

try {
pmd.run(true, true, new MySimpleRunnable());
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

 

Progress Dialog

 

TitleAreaDialog

"A dialog that has a title area for displaying a title and an image as well as a common area for displaying a description, a message, or an error message. This dialog class may be subclassed."

This is the class that i often use for "About MyCompany" kind of dialogs.

public class TitleAreaDialog_Ex extends TitleAreaDialog {

public TitleAreaDialog_Ex(Shell parentShell) {
super(parentShell);
}

@Override
protected Control createDialogArea(Composite parent) {
Composite contents = new Composite(parent, SWT.NONE);
contents.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

setTitle("This is the Title Area Title");
setMessage("This is the Title Area Description");

new Label(contents, SWT.LEFT).setText("Hello World in Content Area");

Dialog.applyDialogFont(parent);

Point defaultMargins = LayoutConstants.getMargins();
GridLayoutFactory.fillDefaults().numColumns(2).margins(defaultMargins.x, defaultMargins.y).generateLayout(contents);

return contents;
}

public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Title Area Shell");
shell.pack();
TitleAreaDialog taDialog = new TitleAreaDialog_Ex(shell);
taDialog.setTitleAreaColor(new RGB(0, 100, 200));
taDialog.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

 

TitleArea Dialog

 

ElementListSelectionDialog

"A class to select elements out of a list of elements."

	    ElementListSelectionDialog listDialog = new ElementListSelectionDialog(shell,new LabelProvider());	    
listDialog.setTitle("This is Element List Title");
listDialog.setMessage("This is Element List Message");
listDialog.setElements(list.toArray());
listDialog.open();

 

ElementListSelectionDialog

 

ListDialog

"A dialog that prompts for one element out of a list of elements. Uses IStructuredContentProvider to provide the elements and ILabelProvider to provide their labels."

	    ListDialog ld = new ListDialog(shell);
ld.setAddCancelButton(true);
ld.setContentProvider(new ArrayContentProvider());
ld.setLabelProvider(new LabelProvider());
ld.setInput(list.toArray());
ld.setInitialSelections(list.toArray());
ld.setTitle("Select # of Nobel Prize Nominations :");
ld.open();

 

ListDialog

 

TwoPaneElementSelector

"A list selection dialog with two panes. Duplicated entries will be folded together and are displayed in the lower pane (qualifier)."

	    TwoPaneElementSelector elementSelector = new TwoPaneElementSelector(shell, labelProvider, labelProvider);
elementSelector.setTitle("Two Pane Element Selector");
elementSelector.setElements(new String[] {"One", "Two", "Three"});
elementSelector.setLowerListLabel("Lower List");
elementSelector.setUpperListLabel("Upper List");
elementSelector.setMultipleSelection(true);
elementSelector.setInitialSelections(new String[] {"One", "Two"});
elementSelector.open();

 

TwoPaneElementDialog

List SelectionDialog

"A standard dialog which solicits a list of selections from the user. This class is configured with an arbitrary data model represented by content and label provider objects. The getResult method returns the selected elements."

	    ListSelectionDialog lsd = new ListSelectionDialog(window.getShell(), list, new ArrayContentProvider(), new LabelProvider(), "ListSelectionDialog Message");
lsd.setInitialSelections(list.toArray());
lsd.setTitle("Select # of Nobel Prize Nominations :");
lsd.open();

 

ListSelectionDialog

ElementTreeSelectionDialog

 "A dialog class to select elements out of a tree structure."

		ElementTreeSelectionDialog treeDialog = new ElementTreeSelectionDialog(window.getShell(), new MyLabelProvider(), new MyTreeContentProvider());
treeDialog.setInput(nullFamily);
treeDialog.setInitialSelections(nullFamily.getChildren());
treeDialog.setInitialElementSelections(list);
treeDialog.setInitialSelection("One");
treeDialog.setTitle("ElementTreeSelection Title");
treeDialog.setMessage("ElementTreeSelectionDialog Message");
treeDialog.open();

 

ElementTreeSelectionDialog

CheckedTreeSelectionDialog

"A dialog class to select elements out of a tree structure"

		CheckedTreeSelectionDialog checkedtreeDialog = new CheckedTreeSelectionDialog(window.getShell(), new MyLabelProvider(), new MyTreeContentProvider());
checkedtreeDialog.setInput(nullFamily);
checkedtreeDialog.setInitialSelections(nullFamily.getChildren());
checkedtreeDialog.setInitialElementSelections(list);
checkedtreeDialog.setInitialSelection("One");
checkedtreeDialog.setTitle("ElementTreeSelection Title");
checkedtreeDialog.setMessage("ElementTreeSelectionDialog Message");
checkedtreeDialog.open();

 

CheckedTreeSelectionDialog


Some Notes

  • YesNoCancelListSelectionDialog has been Deprecated in 3.3 of Eclipse.
  • RCP Product extensions and custmizations can be done via AboutDialogs.
    • AboutDialog
    • AboutFeaturesDialog
    • AboutPluginsDialog
    • AboutSystemDialog
    Note : Above Dialogs are internal dialogs and not APIs. They are mentioned only as a reference.
  • PrintDialog is intended to be sub-classes by the clients and use it for identifying the printers and other parameters for print job.
  • SaveAsDialog is not available in Eclipse 3.3

Conclusion

Dialogs are a great way to present simple data and receive user input. Its very important to understand several Dialogs provided by JFace and use them appropriately.

More Information

The Java Zone is brought to you by Stormpath—a complete, pre-built User Management API. Want to learn how to use JWTs to protect microservices from CSRF and more? Check out this on-demand webinar with our Java Developer Evangelist, Micah Silverman.

Topics:

Published at DZone with permission of Suresh Krishna. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}