JDialog

Java JDialog example

This is a tutorial of how to create dialog windows, using the JDialog class of the javax.swing package.

The Swing API provides libraries to create a Graphical User Interface in platform independent way. It follows the MVC architecture. It consists of UI elements, which are the visual elements that a user interacts with, layouts, which define the use of the UI elements and Events that occur from the user interaction with UI elements.

Here, we will talk about the JDialog class, which is used to create dialog windows. It can either be used directly to create a custom dialog, or we can invoke methods provided by JOptionPane to create many dialogs.

Dialog windows are usually used as error messages or warnings, but may can have images, directory trees, or just about anything compatible with the main Swing Application that manages them. A dialog can belong to another dialog or a frame, or it can stand alone like a JFrame. It can also be modal, meaning that when it opens no other window of the application can be accessed until it is closed.

In the example below, the MyJDialog class extends the JDialog, thus allowing us to implement our own JDialog example:

  • The class overrides the createRootPane() method of the JDialog class, where it creates the JRootPane. It is the rootPane, that will contain all given components.
  • In the basic constructor of the class, the super constructor is called, with the parent JFrame and the String title of the dialog window. Then a new Point is created with specific dimensions, which are used in the setLocation(int x, int y) API method of the JDialog.
  • Create a message:
    A new JPanel is created with a new Jlabel, and the String message passed in the constructor. It is added to the Container, with the getContentPane() API method of JDialog and add(Component comp) API method of Container.
  • Create a button:
    Again, we create a JPanel with a JButton, which is an implementation of a “push” button. The button uses an action listener, making use of addActionListener(ActionListener l) API method of AbstractButton. The action listener is a custom implementation of ActionListener. MyActionListener implements ActionListener and overrides its actionPerformed(ActionEvent e) API method, where it disposes of the dialog window.
    Again, the getContentPane() API method of JDialog and add(Component comp) API method of Container are used to add the button at the end of the container page.
  • In createRootPane() method, the getKeyStroke(String s) method of KeyStroke class is used to set the "ESCAPE" keystroke. A new AbstractAction is also created, implementing the actionPerformed(ActionEvent e) method, where setVisible(false) and dispose() API methods are used, to make the window invisible and dispose of it. Both the KeyStroke defined and the AbstractAction are used in the JRootPane created. The getInputMap(int condition) method of JRootPane is used to get the inputmap when the component has focus. In the inputmap we set the keystroke to "ESCAPE". We also get the ActionMap used to determine what Action to fire for particular keyStroke binding, with getActionMap() API method of JRootPane, so this is where we bind the action and the keystroke.
  • Finally, the setDefaultCloseOperation(int operation) is used to set the operation that will happen by default when the user initiates a “close” on this dialog. The pack() API method is used so that the window to be sized to fit the preferred size and layouts of its subcomponents. And the setVisible(boolean b) is set to true, so that the window is visible.

In order to run our example, we have created a main() method, where we create a new JDialog instance, with a specific message and a specific title. We also use the setSize(int arg0, int arg1) API method of JDialog to set the size of the window.

Take a look at the code snippet below:

MyJDialog.java

package com.javacodegeeks.snippets.enterprise;

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

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

public class MyJDialog extends JDialog {

	private static final long serialVersionUID = 1L;

	public MyJDialog(JFrame parent, String title, String message) {
		super(parent, title);
		System.out.println("creating the window..");
		// set the position of the window
		Point p = new Point(400, 400);
		setLocation(p.x, p.y);

		// Create a message
		JPanel messagePane = new JPanel();
		messagePane.add(new JLabel(message));
		// get content pane, which is usually the
		// Container of all the dialog's components.
		getContentPane().add(messagePane);

		// Create a button
		JPanel buttonPane = new JPanel();
		JButton button = new JButton("Close me");
		buttonPane.add(button);
		// set action listener on the button
		button.addActionListener(new MyActionListener());
		getContentPane().add(buttonPane, BorderLayout.PAGE_END);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		pack();
		setVisible(true);
	}

	// override the createRootPane inherited by the JDialog, to create the rootPane.
	// create functionality to close the window when "Escape" button is pressed
	public JRootPane createRootPane() {
		JRootPane rootPane = new JRootPane();
		KeyStroke stroke = KeyStroke.getKeyStroke("ESCAPE");
		Action action = new AbstractAction() {
			
			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent e) {
				System.out.println("escaping..");
				setVisible(false);
				dispose();
			}
		};
		InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
		inputMap.put(stroke, "ESCAPE");
		rootPane.getActionMap().put("ESCAPE", action);
		return rootPane;
	}

	// an action listener to be used when an action is performed
	// (e.g. button is pressed)
	class MyActionListener implements ActionListener {

		//close and dispose of the window.
		public void actionPerformed(ActionEvent e) {
			System.out.println("disposing the window..");
			setVisible(false);
			dispose();
		}
	}

	public static void main(String[] a) {
		MyJDialog dialog = new MyJDialog(new JFrame(), "hello JCGs", "This is a JDialog example");
		// set the size of the window
		dialog.setSize(300, 150);
	}
}

When running the example, the window is created, as shown below:

My JDialog example
My JDialog example

Now, you can close the window, either by hitting the ESCAPE keystroke, or by clicking the button.

 
This was an example of JDialog class.

Download
You can download the full source code of this example here : JavaJDialogExample.zip

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button