Java Swing Tutorial - Java Swing JDialog








A JDialog is a top-level Swing container to host components and display a dialog.

Creating a dialog window is very simple: just create a new class that inherits from the JDialog class.

By default, a JDialog uses a BorderLayout as the layout manager.

To center the JDialog within a frame, assuming that myFrame exists

dateTimeDialog.setLocationRelativeTo(myFrame);

To position the JDialog in the center of screen

dateTimeDialog.setLocationRelativeTo(null);

We can create a JDialog with an owner, which could be another JDialog, a JFrame, or a JWindow.

By specifying an owner for a JDialog, we are creating a parent-child relationship.

When the owner of a JDialog is closed, the JDialog is also closed. When the owner is minimized or maximized, the JDialog is also minimized or maximized.

A JDialog with an owner is always displayed on top of its owner.

We can specify an owner of a JDialog in its constructors.

When we create a JDialog using its no-args constructor, a hidden Frame is created as its owner.

We can create a JDialog with null as its owner, and in that case, it does not have an owner.

By default, a JDialog is resizable. To disable the resize, calling its setResizable(false) method.

Based on focus behavior of a JDialog, it can be categorized as

  • Modal
  • Modeless

When a modal JDialog is displayed, it blocks other displayed windows in the application. To make a JDialog modal, we can use its setModal(true) method.

Some of the constructors of the JDialog allows us to set whether the JDialog should be modal or modeless.

A modeless JDialog does not block any other displayed windows in the application.

By default, a JDialog is modeless.

A JDialog can have one of the four types of modalities. They are defined by the four constants in java.awt.Dialog.ModalityType enum:

  • MODELESS - JDialog will not block any windows
  • DOCUMENT_MODAL - JDialog will block any windows in its parent hierarchy. It will not block any window in its child hierarchy.
  • APPLICATION_MODAL - JDialog will block any windows in that Java application, except those in its child hierarchy.
  • TOOLKIT_MODAL - JDialog will block any windows run from the same toolkit, except those in its child hierarchy. In a Java application, it is the same as APPLICATION_MODAL. It is useful in applets or Java Web Start.

We can specify the modality type of a JDialog in its constructor or by using its setModalityType() method.