9.2. Creating Dialogs

Problem

You need some input from the user, and a dialog box would be perfect.

Solution

Create a new shell, configure it as a dialog, display it, and recover the data the user entered.

Discussion

SWT has message boxes and a number of prebuilt dialogs that come with it, such as the FileDialog class that creates file dialogs or the FontDialog class that enables users to choose a font. But if you need more than those prebuilt dialogs, you can build your own custom dialog. In this example, we’re going to assume you want to confirm the user’s decision to delete a file. When the user clicks a button labeled Delete File, the application (DialogApp at this book’s site) displays a confirming dialog with OK and Cancel buttons. You can then determine which one the user clicked.

The application starts by creating a shell with the Delete File button and a text widget in whch we’ll display the response to the user’s button click:

Display display = new Display( );
Shell shell = new Shell(display);
shell.setText("Dialog Example");
shell.setSize(300, 200);
shell.open( );

final Button button = new Button(shell, SWT.PUSH);
button.setText("Delete File");
button.setBounds(20, 40, 80, 25);

final Text text = new Text(shell, SWT.SHADOW_IN);
text.setBounds(140, 40, 100, 25);
         .
         .
         .

To create a dialog, you create a shell and give it the style SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM, making it an application-modal dialog (the user must dismiss it before continuing with the application) and styling ...

Get Eclipse Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.