Dialogs in Java SWT

In this part of the Java SWT tutorial, we introduce dialogs.

Dialog windows or dialogs are an indispensable part of most modern GUI applications. A dialog is defined as a conversation between two or more persons. In a computer application a dialog is a window which is used to "talk" to the application. A dialog is used to input data, modify data, change the application settings etc. Dialogs are important means of communication between a user and a computer program.

MessageBox

MessageBox is a simple dialog that provides some information to the user. It can contain messages, icons, and various buttons. Icons and buttons are chosen with available MessageBox styles. For instance, the SWT.ICON_ERROR flag puts an error icon on the dialog.

MessageBoxEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This example shows a simple MessageBox.
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class MessageBoxEx {
    
    private Shell shell;
    
    public MessageBoxEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {
        
        shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);
        
        RowLayout layout = new RowLayout();
        layout.marginTop = 50;
        layout.marginBottom = 150;
        layout.marginLeft = 50;
        layout.marginRight = 150;
        shell.setLayout(layout);
        
        Button msgBtn = new Button(shell, SWT.PUSH);
        msgBtn.setText("Show message");
        msgBtn.addListener(SWT.Selection, event -> doShowMessageBox());
        
        shell.setText("Message box");
        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }      
    }
    
    private void doShowMessageBox() {
        
        int style = SWT.ICON_INFORMATION | SWT.OK;

        MessageBox dia = new MessageBox(shell, style);
        dia.setText("Information");
        dia.setMessage("Download completed."); 
        dia.open();
    }    
    
    @SuppressWarnings("unused")
    public static void main(String[] args) {
        
        Display display = new Display();
        MessageBoxEx ex = new MessageBoxEx(display);
        display.dispose();
    }    
}

There is one push button on the window. Clicking on the button displays an information message dialog.

int style = SWT.ICON_INFORMATION | SWT.OK;

The dialog contains an Information icon and an Ok button.

MessageBox dia = new MessageBox(shell, style);

An instance of the MessageBox is created, taking the style as the second parameter.

dia.setText("Information");

The dialog's title is set with the setText() method.

dia.setMessage("Download completed."); 

The message is set with the setMessage() method.

MessageBox
Figure: MessageBox

Application closing

In order to prevent data loss, data-centric applications often show a confirmation dialog when being closed. Only after the dialog is confirmed, the application terminates.

MessageBoxEx2.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This example shows a confirmation dialog
 * when its closing is initiated.
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class MessageBoxEx2 {

    private Shell shell;

    public MessageBoxEx2(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {

        shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);

        shell.addListener(SWT.Close, event -> doShowMessageBox(event));

        shell.setText("Message box");
        shell.setSize(350, 300);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    private void doShowMessageBox(Event event) {

        int style = SWT.APPLICATION_MODAL | SWT.ICON_QUESTION | SWT.YES
                | SWT.NO;

        MessageBox messageBox = new MessageBox(shell, style);
        messageBox.setText("Information");
        messageBox.setMessage("Really close application?");
        event.doit = messageBox.open() == SWT.YES;
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Display display = new Display();
        MessageBoxEx2 ex = new MessageBoxEx2(display);
        display.dispose();
    }
}

This example shows a confirmation dialog when its closing is initiated.

shell.addListener(SWT.Close, event -> doShowMessageBox(event));

We hook a listener to the SWT.Close event type.

int style = SWT.APPLICATION_MODAL | SWT.ICON_QUESTION | SWT.YES
        | SWT.NO;

The confirmation dialog is modal and contains a Question icon and Yes and No buttons. (Modal dialogs block the main application until they are dismissed.)

event.doit = messageBox.open() == SWT.YES;

Setting the doit event to false cancels it; setting to true allows it.

Directory dialog

DirectoryDialog is a dialog which is used to select a path to a certain directory.

DirectoryDialogEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This example shows a directory dialog.
 *
 * Author: Jan Bodnar 
 * Website: zetcode.com 
 * Last modified: June 2015
 */

public class DirectoryDialogEx {

    private Shell shell;
    private Label status;

    public DirectoryDialogEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {

        shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);

        status = new Label(shell, SWT.BORDER);
        status.setText("Ready");

        FormLayout layout = new FormLayout();
        shell.setLayout(layout);

        FormData labelData = new FormData();
        labelData.left = new FormAttachment(0);
        labelData.right = new FormAttachment(100);
        labelData.bottom = new FormAttachment(100);
        status.setLayoutData(labelData);

        shell.addListener(SWT.MouseDown, event -> onMouseDown());

        shell.setText("DirectoryDialog");
        shell.setSize(350, 250);
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    private void onMouseDown() {

        DirectoryDialog dialog = new DirectoryDialog(shell);
        String path = dialog.open();

        if (path != null) {
            status.setText(path);
        }
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Display display = new Display();
        DirectoryDialogEx ex = new DirectoryDialogEx(display);
        display.dispose();
    }
}

In our example, we select a directory with the DirectoryDialog and display its path in the statusbar. The dialog is shown by clicking on the area of the window.

shell.addListener(SWT.MouseDown, event -> onMouseDown());

A mouse listener for the SWT.MouseDown event is added to the shell. When we press a mouse button on the window, the onMouseDown() method is invoked.

DirectoryDialog dialog = new DirectoryDialog(shell);

A DirectoryDialog is created.

String path = dialog.open();

We get the path to the selected directory.

if (path != null) {
    status.setText(path);
}

If the path is not null, we show the path in the status label.

Directory dialog
Figure: Directory dialog

FontDialog

FontDialog is a dialog for selecting fonts. It is typically used in applications that do some text editing or formatting.

FontDialogEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This example shows a font dialog.
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class FontDialogEx {
    
    private Shell shell;
    private Label label;

    public FontDialogEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {
        
        shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);
        
        RowLayout layout = new RowLayout();
        layout.marginHeight = 100;
        layout.marginWidth = 100;
        shell.setLayout(layout);          

        label = new Label(shell, SWT.NONE);
        label.setText("ZetCode Java SWT tutorial");
        
        shell.addListener(SWT.MouseDown, event -> onMouseDown());        
        shell.setText("FontDialog");
        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }        
    }
    
    private void onMouseDown() {

        FontDialog dialog = new FontDialog(shell);
        FontData fdata = dialog.open();

        if (fdata != null) {

            Font font = new Font(shell.getDisplay(), fdata);
        
            label.setFont(font);
            label.pack();
            shell.pack();
            font.dispose();
        }   
    }    

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        
        Display display = new Display();
        FontDialogEx ex = new FontDialogEx(display);
        display.dispose();
    }
}

In the code example, we use the FontDialog to change the font of a label.

FontDialog dialog = new FontDialog(shell);

The FontDialog is created.

Font font = new Font(shell.getDisplay(), fdata);

A Font object is created from the font data, returned by the font dialog.

label.setFont(font);

The font is applied to the label with the setFont() method.

label.pack();
shell.pack();

The pack() method adapts the label and the shell to the new font type.

font.dispose();

Font is an OS resource; therefore, it must be disposed when not needed anymore.

FontDialog
Figure: FontDialog

ColorDialog

ColorDialog is a dialog for selecting a colour.

ColorDialogEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This example shows a color dialog.
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class ColorDialogEx {
    
    private Shell shell;
    private Label label;

    public ColorDialogEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {
        
        shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);
        
        RowLayout layout = new RowLayout();
        layout.marginHeight = 100;
        layout.marginWidth = 100;
        shell.setLayout(layout);             

        label = new Label(shell, SWT.NONE);
        label.setText("ZetCode Java SWT tutorial");
        
        shell.addListener(SWT.MouseDown, event -> onMouseDown());
        
        shell.setText("ColorDialog");
        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }        
    }
    
    private void onMouseDown() {
        
        ColorDialog dialog = new ColorDialog(shell);
        RGB rgb = dialog.open();
        
        if (rgb != null) {
            Color col = new Color(shell.getDisplay(), rgb);
            label.setForeground(col);
            col.dispose();
        }            
    }    

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        
        Display display = new Display();
        ColorDialogEx ex = new ColorDialogEx(display);
        display.dispose();
    }
}

The example is very similar to the previous one. This time we change the colour of the label. The ColorDialog is shown by clicking on the window area.

ColorDialog dialog = new ColorDialog(shell);

We create the ColorDialog.

RGB rgb = dialog.open();

With the ColorDialog's open() method, we get the RGB value.

Color col = new Color(shell.getDisplay(), rgb);
label.setForeground(col);

We get the colour value and modify the colour of the label.

col.dispose();

Color is an OS resource, so we dispose it when it is not needed anymore.

ColorDialog
Figure: ColorDialog

FileDialog

FileDialog is used to select a name of a file.

FileDialogEx.java
package com.zetcode;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

/**
 * ZetCode Java SWT tutorial
 *
 * This example shows a file dialog.
 *
 * Author: Jan Bodnar
 * Website: zetcode.com
 * Last modified: June 2015
 */

public class FileDialogEx {

    private Shell shell;
    private Label label;

    public FileDialogEx(Display display) {

        initUI(display);
    }

    private void initUI(Display display) {
        
        shell = new Shell(display, SWT.SHELL_TRIM | SWT.CENTER);

        RowLayout layout = new RowLayout();
        layout.marginHeight = 50;
        layout.marginWidth = 50;
        shell.setLayout(layout);

        label = new Label(shell, SWT.NONE);
        String homeDir = System.getProperty("user.home"); 
        label.setText(homeDir);
        label.pack();

        shell.addListener(SWT.MouseDown, event -> onMouseDown());

        shell.setText("FileDialog");
        shell.pack();
        shell.open();

        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }
    
    private void onMouseDown() {

        FileDialog dialog = new FileDialog(shell, SWT.OPEN);

        String[] filterNames = new String[] 
            {"Java sources", "All Files (*)"};

        String[] filterExtensions = new String[] 
            {"*.java", "*"};

        dialog.setFilterNames(filterNames);
        dialog.setFilterExtensions(filterExtensions);

        String path = dialog.open();
        
        if (path != null) {
            
            label.setText(path);
            label.pack();
            shell.pack();
        }        
    }

    @SuppressWarnings("unused")
    public static void main(String[] args) {

        Display display = new Display();
        FileDialogEx ex = new FileDialogEx(display);
        display.dispose();
    }
}

The code example uses the FileDialog to select a file. The dialog uses a filter to show only the Java sources. The name of the chosen file is shown in the label.

label = new Label(shell, SWT.NONE);
String homeDir = System.getProperty("user.home"); 
label.setText(homeDir);
label.pack();

At the start, the label widget displays the user's home directory.

FileDialog dialog = new FileDialog(shell, SWT.OPEN);

We create a FileDialog with the SWT.OPEN flag. The dialog can be used both to open or save files. The save behaviour of the dialog is enabled with the SWT.SAVE constant.

String[] filterNames = new String[] 
{"Java sources", "All Files (*)"};

String[] filterExtensions = new String[] 
    {"*.java", "*"};

dialog.setFilterNames(filterNames);
dialog.setFilterExtensions(filterExtensions);

We use two filters; one for Java sources and one for all file types.

String path = dialog.open();

The path name is retrieved with the FileDialog's open() method.

if (path != null) {
    
    label.setText(path);
    label.pack();
    shell.pack();
}

The path name is set to the label with the setText() method. The label and the shell are adapted to the size of the returned path with the pack() method.

This part of the Java SWT tutorial was about dialogs in SWT.