There are times when you want a modal window that implements window-specific modality rather than the application-wide modality provided by the standard JDialog class. This article explains the workings of the JModalWindow project [16], which provides two top-level components, called ModalWindows, that introduce such modality. The first ModalWindow class, JModalWindow, is a subclass of JWindow that's generally used for dialogs that block other windows. The second, JModalFrame, is a subclass of JFrame that can be used either as a blocked window or as a blocking window. Both classes implement an interface named InputBlocker.
Why create a ModalWindow instead of using the standard JDialog component? We were working on a pension-planner application to give users insight into their financial situations before and after retirement. This was done with the aid of a financial graphic. Throughout the application, help information for various pension-specific terms was available in a separate help window. In order to make comparisons, the user should be able to change different variables that influence pension savings. While doing this, the underlying financial graphic had to be blocked. A JDialog could have been used, but then the necessary help window would have also been blocked, and thus useless. Furthermore, the title bar presented by JDialog didn't fit in with the rest of the look and feel of the application.
I searched the Internet for a possible solution for our problem and found several suggestions, but they all had drawbacks or loopholes. That is why I decided to create my own modal window implementation based on the ideas that came closest to our needs. The JModalWindow project [17] is an open source version of our solution to this challenge and is part of the JavaDesktop [18] community at java.net [19].
It helps to have a common language when referring to the various windows involved. The window to be blocked is known as the parent window or owner; another term for blocked is busy. The window blocking the parent is the child window. A parent window can have more than one child window blocking it. Each child can block its parent and, in recently added functionality, some additional windows. Ideally, the parent window and the child window should both be ModalWindows; at the very least, they should both implement the InputBlocker interface.
An example will clarify these concepts. Here is a snapshot of a GUI produced by a JModalWindow that is
modal with respect to a JModalFrame:

Figure 1. A snapshot of a GUI produced by a JModalWindow that is modal with respect to a JModalFrame.
As the preceding figure shows, a JModalFrame's busy status is
marked using a blur effect and stop cursor. You can customize the following
aspects of the display:
X,Y location.The following figure shows the same GUI as the preceding one, but with a line
busy effect, custom stop cursor, and initial Y position relative to the
bottom of the Update button that brought up the dialog. The X position
of the dialog depends on the JModalWindow release. The dialog is
be positioned at the same X position as the button, as long as the dialog
stays onscreen; otherwise it will be moved to the left to keepWindowCompletelyOnScreen.

Figure 2. The same GUI as the preceding one, but with a line busy effect, custom stop cursor, and initial Y position relative to the bottom of the Update button that brought up the dialog.
The following code creates a dialog that is modal relative to the window (owner)
containing returnFocusComponent and that is optionally placed relative
to returnFocusComponent. The dialog has a single button, which
closes the dialog.
private JModalWindow createStatusWindow(
Component returnFocusComponent,
boolean relative,
String text) {
Window owner = SwingUtilities.windowForComponent(returnFocusComponent);
final JModalWindow jmw = new JModalWindow(owner, returnFocusComponent);
jmw.getContentPane().setBackground(bg);
jmw.getContentPane().setForeground(fg);
jmw.getContentPane().setLayout(new GridBagLayout());
JButton jbClose = createJButton("Cancel");
jbClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jmw.dispose();
}
});
BorderLayout bl = new BorderLayout();
jmw.getContentPane().setLayout(bl);
jmw.getContentPane().add(createLabel(text), BorderLayout.CENTER);
jmw.getContentPane().add(jbClose, BorderLayout.SOUTH);
jmw.setSize(300, 75);
if (relative) {
jmw.relativeToOwnerChild(returnFocusComponent);
} else {
jmw.centerOfOwner();
// jmw.centerOfScreen(); //another positioning possibility
}
return jmw;
}
For the best results, the owner should be a ModalWindow.
In the preceding code, the JModalWindow constructor sets up the
dialog, and the relativeToOwnerChild method causes the dialog to be
positioned just under the returnFocusComponent's onscreen representation.
InputBlocker InterfaceBoth JModalFrame and JModalWindow implement an interface
called InputBlocker. The interface defines the following two methods:
public boolean isBusy();public void setBusy(boolean busy, Window blockingWindow);With those methods, it is possible to check whether a window is currently blocked and let any child window signal that it is blocking or unblocking its parent.
Note: The draft version of this article was written based on the sources
of version 1.02. But since then I have added some new functionality that is detailed
in the section Latest Developments and Ideas [20]. One
of those new functionalities led to a third method definition in the InputBlocker
interface:
public void addAdditionalModalToWindow(Window window);With this method, it is possible to add additional windows that should be blocked
at the same time as the parent window. This is the reason why in the next paragraphs
the variable modalToWindows is plural instead of modalToWindow,
which you would expect because a child window only has one parent window.
The isBusy and setBusy methods are useful for the
parent window; the addAdditionalModalToWindow method is useful
for the child window.
To block all keyboard and mouse action for the underlying window, a JBusyPanel
object can be used as a GlassPane for the blocked window. The JBusyPanel,
when activated, consumes all keyboard strokes for the underlying window and
grabs the focus for any mouse action on it.
To make it obvious that the window is blocked, you can apply one of two types of blurring:
BLUR_STYLE_LINEBLUR_STYLE_RASTERThe desired blur style, gap, and color are applied by the paint
method of the JBusyPanel. When blocked, the ModalWindow also
changes the shape of the cursor (see getBusyCursor [21]).
To block the FocusManager in JavaTM 1.3, JBusyPanel overrides
the deprecated method isManagingFocus.
ModalWindowsThe constructors for JModalWindow and JModalFrame
accept the following parameters, as needed:
Window ownerComponent returnFocusString title (JModalFrame only)boolean modalEach ModalWindow constructor performs the following actions:
The appropriate super is called to set the title
for the JFrame and the owner for the JWindow.
(Note: If no owner is specified, the Swing SharedOwnerFrame
is used.)
The optional returnFocus is stored.
The list modalToWindows is set to contain the supplied owner
when this Window is constructed as being modal. Because the parent
isn't blocked yet, the status variable notifiedModalToWindow
is set to true.
The list with blockingWindows is initialized. This Vector
is used to make it possible to have multiple modal child windows.
The JBusyPanel that will block this window is initialized with
the following settings:
BLUR_STEP of 2.BLUR_STYLE of the type raster.These settings were chosen because that combination looks best, in my humble opinion. However, if performance is an issue, these values can be changed in your own copy of the source code.
Finally, the WINDOW_EVENT_MASK is used to activate the processing
of WindowEvents.
Each JModalWindow also performs the following initialization:
Creates a raised border to indicate that the window can be dragged.
Activates MOUSE_MOTION_EVENT_MASK for the processing of MouseEvents,
to support dragging of the window.
Each JModalFrame performs the following additional initialization:
Sets up a MinimumFrameSizeAdapter to keep the frame from being
resized smaller than minWidth by minHeight when those
values are supplied through the method setMinSize.
Checks whether a default icon, for which the resource location can be filed
under the key swingx.frame.icon in the UIManager,
is available. If this is the case, the support utility [13] is used to fetch it.
As soon as a child ModalWindow is activated through a call to the method
show, it checks whether it is modal to a parent window stored in
the list modalToWindows. When this is the case and the parent window
implements the interface InputBlocker, its setBusy
method is called to notify that parent window that it is blocked by this child
window. Should the parent window not implement the interface InputBlocker,
then the parent window is only disabled.
Unlike the JDialog behavior, calling the method show
doesn't halt the calling thread. To create the same effect, call the method
wait_for_close after calling show. (Note: This method will be renamed to waitForClose in a later release.)
Note: Activating the window with a call to the method setVisible(boolean visible)
results in an indirect call to the method show. That is the reason why the situation for visible is true isn't handled in the setVisible method itself.
Placement of the ModalWindow is aided with the following helper methods:
centerOfScreen, centerOfOwner, and relativeToOwnerChild.
(See support utility [22] for a description of these methods.)
Upon closing a child ModalWindow through a WindowEvent.WINDOW_CLOSED
(see the methods processWindowEvent and close), or a call
to the method setVisible, the ModalWindow calls the method
restoreOwner to check whether it is modal to a parent window stored
in the list modalToWindows. When this is the case, the parent window
is notified that this child window is no longer blocking it by a call to the
parent window's method setBusy or, if the parent window doesn't
implement the InputBlocker, by enabling it.
Because a call to setVisible(false) results in a WindowEvent.WINDOW_CLOSED
event and thus in multiple calls to the method restoreOwner, the
variable notifiedModalToWindow is used to prevent multiple calls
to the parent window's method setBusy. This helps when the parent
window's setBusy implementation doesn't handle multiple invocations
by the same child window well. (My first implementation, for example, decremented
a blockedCounter.)
If the parent window is no longer blocked by any child window, the focus is
returned to the optional returnFocus component, if it's supplied.
Finally, a call to the method release is made to notify any waiting threads that were halted by a call to the
method waitForClose.
When a ModalWindow is blocked by a child window calling its setBusy method, the following actions are
taken:
Retrieve the default or the custom busy cursor.
If the ModalWindow is not already blocked, save the current cursor
and set the cursor to the busy cursor.
JModalFrame only: Save current resizable status
if the frame is not already blocked, and disable the resizing of the frame.
Enable the JBusyPanel glass pane.
Add the calling child window to the list of blockingWindows.
Force the glass pane to get the focus so that it consumes KeyEvents.
Set the cursor for the glass pane to the busy cursor.
Note: Setting the window cursor and the glass pane cursor in this order
works around the Win32 problem where you have to move the mouse one pixel
to get the cursor to change.
To check whether a ModalWindow is currently blocked, a call to the method
isBusy results in a confirmation if there are any known blockingWindows. As soon as a ModalWindow is blocked, its behavior changes in the
following situations:
JModalFrame only: A call to getDefaultCloseOperation
always returns JFrame.DO_NOTHING_ON_CLOSE.
WindowEvents are handled differently by processWindowEvent:
JModalFrame only: WindowEvent.WINDOW_ICONIFIED
is reversed by setting the state back to NORMAL (see the
method checkIconifyAllowed). This behavior will be changed
with the release of version 1.05. (For more information, see the section Latest Developments and Ideas [20].)
JModalFrame only: WindowEvent.WINDOW_ACTIVATED
results in moving its child windows to the front and in restoring
the state of its child frames to NORMAL. (See the method checkForBlockingWindows, which will be renamed to checkActivationAllowed in a later release.)
WindowEvent.WINDOW_CLOSING is not allowed (see the method
tryToDispose).
When a ModalWindow is unblocked by a child window calling its setBusy
method, the following actions occur:
Remove the calling child window from the list of blockingWindows.
Reset the cursor for the glass pane to the old cursor and disable the glass pane.
Try to retrieve focus in the ModalWindow.
JModalFrame only: Reset the resizable status
to the stored wasResizable value.
Reset the ModalWindow's cursor to the old cursor.
Note: Setting the glass pane cursor and the window cursor in this order
works around the Win32 problem where you have to move the mouse one pixel
to get the cursor to change.
To support the dragging of a JModalWindow, the method processMouseMotionEvent
checks the following things:
checkDragZoneDRAG_BORDER_DISTANCE; currently only a value of
1 seems to work properly), then the cursor is changed to the MOVE_CURSOR
to indicate the possibility of dragging the window across the screen, and
the current mouse position is stored in priorDragLocation.dragWindowMOVE_CURSOR
shape and a priorDragLocation is available, then the window is
moved along the delta x and delta y relative to the current
mouse position, and the priorDragLocation is reset to null
to signal that the last mouse-drag event is handled completely. If there was
no priorDragLocation available, then the current mouse position
is saved for the next mouse drag event.To decorate JModalWindows with a raised border the following methods
are overridden: paint, setBackground, and setForeground.
The Utils class handles various handy functions for JModalWindow
and JModalFrame:
getBusyCursorswingx.busy.cursor in UIManager. A Win32 problem
requires the cursor to be 32 x 32.getIcongetStopImagegetMissingImagecenterOfScreencenterOfOwnerSCREEN_SAFETY_MARGIN, just in case of operating system
toolbars situated there.relativeToOwnerChildSCREEN_SAFETY_MARGIN.keepWindowOnScreenWindow at the specified x,y location,
adjusting the location if it results in the window falling outside of the
screen and becoming unreachable. This method also uses some slack at the edges of the screen with SCREEN_SAFETY_MARGIN.
(Note: This method will be renamed to keepWindowPartiallyOnScreen because of the introduction of another method called keepWindowCompletelyOnScreen.)The Utils class also provides the following functionality, which
isn't currently used by the JModalWindow and JModalFrame
classes:
updateComponentTreeUIRecent additions to the JModalWindow project have been guided by discussions in a variety of forums. For example, one question on whether it is possible to make a dialog modal for some frames and non-modal
for others led to the addition of the method addAdditionalModalToWindow(Window window) to the InputBlocker interface (link to post [24]).
A comment on a Spanish-language forum pointed out an additional use of modal windows due to the feature that a blocked JModalFrame, upon activation, automatically moves the blocking child window to the front. (Note: In a later release this feature will also be added for the mouse click in a blocked JModalWindow.) Here is a translated excerpt:
When using a modal dialog in a Swing application the following undesirable effect takes place: when the user changes to another application and back to the Java application, the modal window is hidden under the main window. Due to the nature of modality, you cannot interact with the main one, and to top it all, the only way to return to the modal dialog is to use the combination of
Alt+Tabkeys ( link to original [25]).
This discussion also triggered me to complete the project with a JModalDialog
with the same functionality as the JDialog; in other words, blocking
all active frames and windows, but using the same approach as the JModalFrame
and thus creating the same visual effect. Because the InputBlocker now had
the additional method addAdditionalModalToWindow(Window window),
it was possible to create a simple JModalDialog by extending it
from the JModalFrame and just markAllWindows(), except
for the dialog itself and the Swing shared owner frame, to the list of windows
that must be blocked. For a JModalDialog to work properly, all used
windows should be ModalWindows or, at the very least, implement InputBlocker,
because you can call setEnabled(false) only so many times.
Another user asked in a forum posting if I had noticed a severe flicker when one or two modal windows are opened. Once I knew where to look, I saw a rather annoying flicker that I had never noticed before. The flicker was caused
by the call to setResizable(false). That is why I changed the way
resizing is prohibited when the frame is blocked (link to post [26]).
As a result of an issue reported on a problem with the use of window positioning relativeToOwnerChild in a dual-monitor environment, I added support for the GraphicsConfiguration and the use of its supplied getBounds() method for correct window positioning.
The following cosmetic changes were made, which in some cases provide more leeway than one would normally expect for modal windows:
JModalHelper was introduced.activateFirstAvailableBlockingWindow(WindowEvent windowEvent) was added to the InputBlocker for the prior mentioned feature that a blocked JModalFrame upon activation automatically moves the blocking child window to the front.JModalFrame is allowed to be iconified.toFront before is it de-iconified, this problem doesn't manifest itself anymore.If you want to find out about some of the dirty details that led to some of the choices, just check the issue list [27].
As always, if a standard Swing component meets your needs, you are encouraged to use it. In the case where you are looking for a window that does not block the entire application but is modal only with respect to some of your open windows, you may want to consider using JModalWindow. Visit the JModalWindow project [17] home. I look forward to your feedback and suggestions for further enhancements and comments on how you may be using this project in ways that we may not have anticipated.
Finally, if you want to use modal windows with JavaTM 1.3, contact me for the 1.3 source code. If there is enough interest we could also create a project branch for a 1.3 version.
A runnable .jar, which was used to create the screenshots and is based on the above shown sample code, is available for download [28] at the JModalWindow project [16].
I would like to mention the people whose ideas contributed to the creation of this project (in alphabetical order):
I would like to thank the people whose support contributed to the existence of this project (in alphabetical order):
Links:
[1] http://www.java.net/author/jene-jasper
[2] http://www.java.net/article/2004/08/27/jmodalwindow-project#Examples
[3] http://www.java.net/article/2004/08/27/jmodalwindow-project#InputBlocker
[4] http://www.java.net/article/2004/08/27/jmodalwindow-project#VandB
[5] http://www.java.net/article/2004/08/27/jmodalwindow-project#Constructing
[6] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#AandB
[7] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#DandU
[8] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#Blocked
[9] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#BlockedBehavior
[10] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#Unblocked
[11] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#Drag
[12] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#Border
[13] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#Utils
[14] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#Development
[15] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#Conclusion_and_Credits
[16] https://jmodalwindow.dev.java.net/
[17] https://jmodalwindow.dev.java.net
[18] http://community.java.net/javadesktop/
[19] http://www.java.net
[20] http://www.java.net/article/2004/08/27/jmodalwindow-project#Development
[21] http://www.java.net/pub/a/today/2004/09/07/modal.html?page=2#getBusyCursor
[22] http://www.java.net/%3Ccs_comment
[23] http://www.java.net/article/2004/08/27/jmodalwindow-project#getMissingImage
[24] http://forum.java.sun.com/thread.jsp?forum=422&thread=480532
[25] http://www.javahispano.org/news.item.action?id=559083498
[26] http://forum.java.sun.com/thread.jsp?forum=57&thread=489175
[27] https://jmodalwindow.dev.java.net/issues/buglist.cgi?issue_status=UNCONFIRMED&issue_status=NEW&issue_status=STARTED&issue_status=REOPENED&issue_status=RESOLVED&issue_status=VERIFIED&issue_status=CLOSED
[28] https://jmodalwindow.dev.java.net/stable/swingx_v0105_sample.jar
[29] http://www.quobell.nl/