Home  Contents

Java Swing 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.

In Java Swing toolkit, we can create two kinds of dialogs. Custom dialogs and standard dialogs. Custom dialogs are dialogs, created by the programmer. They are based on the JDialog class. Standard dialogs predefined dialogs available in the Swing toolkit. For example JColorChooser or JFileChooser. These are dialogs for common programming tasks like showing text, receiving input , loading and saving files etc. They save programmer's time and enhance using some standard behaviour.

There are two basic types of dialogs: modal and modeless. Modal dialogs block input to other top level windows. Modeless dialogs allow input to other windows. What type of dialog to use, depends on the circumstances. An open file dialog is a good example of a modal dialog. While choosing a file to open, no other operation should be permitted. A typical modeless dialog is a find text dialog. It is handy to have the ability to move the cursor in the text control and define, where to start the finding of the particular text.

A simple custom dialog

In the following example we create a simple custom dialog. It is a sample about dialog, found in most GUI applications, usually located in the help menu.

package zetcode;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;

class AboutDialog extends JDialog {

    public AboutDialog() {

        initUI();
    }

    public final void initUI() {

        setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        add(Box.createRigidArea(new Dimension(0, 10)));

        ImageIcon icon = new ImageIcon("notes.png");
        JLabel label = new JLabel(icon);
        label.setAlignmentX(0.5f);
        add(label);

        add(Box.createRigidArea(new Dimension(0, 10)));

        JLabel name = new JLabel("Notes, 1.23");
        name.setFont(new Font("Serif", Font.BOLD, 13));
        name.setAlignmentX(0.5f);
        add(name);

        add(Box.createRigidArea(new Dimension(0, 50)));

        JButton close = new JButton("Close");
        close.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                dispose();
            }
        });

        close.setAlignmentX(0.5f);
        add(close);

        setModalityType(ModalityType.APPLICATION_MODAL);

        setTitle("About Notes");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setSize(300, 200);
    }
}

public class SimpleDialog extends JFrame {

    public SimpleDialog() {

        initUI();
    }

    public final void initUI() {

        JMenuBar menubar = new JMenuBar();

        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);

        JMenu help = new JMenu("Help");
        help.setMnemonic(KeyEvent.VK_H);

        JMenuItem about = new JMenuItem("About");
        help.add(about);

        about.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                AboutDialog ad = new AboutDialog();
                ad.setVisible(true);
            }
        });

        menubar.add(file);
        menubar.add(help);
        setJMenuBar(menubar);

        setTitle("Simple Dialog");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                SimpleDialog sd = new SimpleDialog();
                sd.setVisible(true);
            }
        });
    }
}

The sample code will popup a small dialog box. The dialog will display an icon a text and one close button.

class AboutDialog extends JDialog {

The custom dialog is based on the JDialog class.

setModalityType(ModalityType.APPLICATION_MODAL);

Here we make the dialog modal.

setDefaultCloseOperation(DISPOSE_ON_CLOSE);

Here we set the default close operation.

AboutDialog ad = new AboutDialog();
ad.setVisible(true);

Here we display the about dialog, from the menu of the main frame.

Simple custom dialog
Figure: Simple custom dialog

Message boxes

Message boxes provide information to the user.

package zetcode;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class MessageBoxes extends JFrame {

    private JPanel panel;

    public MessageBoxes() {

        initUI();
    }

    public final void initUI() {

        panel = new JPanel();
        panel.setLayout(new GridLayout(2, 2));

        JButton error = new JButton("Error");
        JButton warning = new JButton("Warning");
        JButton question = new JButton("Question");
        JButton information = new JButton("Information");

        error.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JOptionPane.showMessageDialog(panel, "Could not open file",
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
        });

        warning.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JOptionPane.showMessageDialog(panel, "A deprecated call",
                        "Warning", JOptionPane.WARNING_MESSAGE);
            }
        });

        question.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JOptionPane.showMessageDialog(panel, "Are you sure to quit?",
                        "Question", JOptionPane.QUESTION_MESSAGE);
            }
        });

        information.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JOptionPane.showMessageDialog(panel, "Download completed",
                        "Question", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        panel.add(error);
        panel.add(warning);
        panel.add(question);
        panel.add(information);

        add(panel);

        setTitle("Message Boxes");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MessageBoxes mb = new MessageBoxes();
                mb.setVisible(true);
            }
        });
    }
}

The example shows an error, question, warning and information message boxes.

panel.setLayout(new GridLayout(2, 2));

We use a GridLayout layout manager to organize buttons, that will popup message boxes.

JButton error = new JButton("Error");
JButton warning = new JButton("Warning");
JButton question = new JButton("Question");
JButton information = new JButton("Information");

Here are the four buttons, that we will use.

JOptionPane.showMessageDialog(panel, "Could not open file", 
    "Error", JOptionPane.ERROR_MESSAGE);

To create a message box, we call the showMessageDialog static method of the JOptionPane class. We provide the component name, message text, title and a message type. The message type is determined by the constant we choose. Available constants are:

  • ERROR_MESSAGE
  • WARNING_MESSAGE
  • QUESTION_MESSAGE
  • INFORMATION_MESSAGE
Question message box
Figure: Question message box

JFileChooser

JFileChooser is a standard dialog for selecting a file from the file system.

package zetcode;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

public class FileChooserDialog extends JFrame {

    private JPanel panel;
    private JTextArea area;

    public FileChooserDialog() {

        initUI();
    }

    public final void initUI() {

        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        ImageIcon open = new ImageIcon("open.png");

        JToolBar toolbar = new JToolBar();
        JButton openb = new JButton(open);

        openb.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                JFileChooser fileopen = new JFileChooser();
                FileFilter filter = new FileNameExtensionFilter("c files", "c");
                fileopen.addChoosableFileFilter(filter);

                int ret = fileopen.showDialog(panel, "Open file");

                if (ret == JFileChooser.APPROVE_OPTION) {
                    File file = fileopen.getSelectedFile();
                    String text = readFile(file);
                    area.setText(text);
                }

            }
        });

        toolbar.add(openb);

        area = new JTextArea();
        area.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JScrollPane pane = new JScrollPane();
        pane.getViewport().add(area);

        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        panel.add(pane);
        add(panel);

        add(toolbar, BorderLayout.NORTH);

        setTitle("FileChooserDialog");
        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public String readFile(File file) {

        StringBuffer fileBuffer = null;
        String fileString = null;
        String line = null;

        try {
            FileReader in = new FileReader(file);
            BufferedReader brd = new BufferedReader(in);
            fileBuffer = new StringBuffer();

            while ((line = brd.readLine()) != null) {
                fileBuffer.append(line).append(
                        System.getProperty("line.separator"));
            }

            in.close();
            fileString = fileBuffer.toString();
        } catch (IOException e) {
            return null;
        }
        return fileString;
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                FileChooserDialog fcd = new FileChooserDialog();
                fcd.setVisible(true);
            }
        });
    }
}

The code example will demonstrate how to use a file chooser dialog in order to load file contents into the text area component.

JFileChooser fileopen = new JFileChooser();

This is the constructor of the file chooser dialog.

FileFilter filter = new FileNameExtensionFilter("c files", "c");
fileopen.addChoosableFileFilter(filter);

Here we define the file filter. In our case, we will have c files with extension .c. We have also the default All files option.

int ret = fileopen.showDialog(panel, "Open file");

Here we show the file chooser dialog. Upon clicking on the open file button, the return value is equal to JFileChooser.APPROVE_OPTION.

if (ret == JFileChooser.APPROVE_OPTION) {
    File file = fileopen.getSelectedFile();
    String text = readFile(file);
    area.setText(text);
}

Here we get the name of the selected file. We read the contents of the file and set the text into the text area.

JFileChooser dialog
Figure: JFileChooser dialog

JColorChooser

JColorChooser is a standard dialog for selecting a color.

package zetcode;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;


public class ColorChooserDialog extends JFrame {

    private JPanel panel;
    private JPanel display;

    public ColorChooserDialog() {

        initUI();
    }

    public final void initUI() {

        panel = new JPanel();
        panel.setLayout(new BorderLayout());
        ImageIcon open = new ImageIcon("color.png");

        JToolBar toolbar = new JToolBar();
        JButton openb = new JButton(open);

        openb.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JColorChooser clr = new JColorChooser();
                Color color = clr.showDialog(panel, "Choose Color",
                        Color.white);
                display.setBackground(color);
            }
        });

        toolbar.add(openb);

        display = new JPanel();
        display.setBackground(Color.WHITE);

        panel.setBorder(BorderFactory.createEmptyBorder(30, 50, 30, 50));
        panel.add(display);
        add(panel);

        add(toolbar, BorderLayout.NORTH);

        setTitle("ColorChooserDialog");
        setSize(400, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                ColorChooserDialog ccd = new ColorChooserDialog();
                ccd.setVisible(true);
            }
        });
    }
}

In the example, we have a white panel. We will change the background color of the panel by selecting a color from the color chooser dialog.

JColorChooser clr = new JColorChooser();
Color color = clr.showDialog(panel, "Choose Color", Color.white);
display.setBackground(color);

This code shows a color chooser dialog. The showDialog() method returns the selected color value. We change the display panel background to the newly selected color.

JColorChooser dialog
Figure: JColorChooser dialog

In this part of the Java Swing tutorial, we have covered dialogs.