To set a JDialog to modal and attach it to a parent window, a parameter has to be passed as JFrame. However, suppose you show a JDialog from a JApplet? Casting it to JFrame will result in an Exception.

Its other constructor parameters are either java.awt.Dialog or java.awt.Window which, from a Swing standpoint should not be mixed with heavyweight components.

Luckily, with JDK 1.6 the SwingUtilities class has a method that can return the window component for any component that you pass as the parameter.

Well, there is no solution to making a Stage window modal when opened from a JFrame. At least not directly. I scoured through countless forums and blog posts but their solutions never made it modal.

A future version of Java FX may solve this problem. In the meantime, this is how I did it in Java FX 2. The same JDialog will be instantiated but set to invisible. I did this by calling the setUndecorated() method to true.

Within the JDialog class, that is where I called the Java FX code to open a Stage window dialog.

So now it is modal. But when you click the JFrame in the task bar in the Windows OS below, the Stage window is not sent to the front. This is not the behavior we want for a modal window, right?

What I did was to add a FocusListener in the JDialog custom class so that when it is in focus (since it is modal), it will call the Stage window object and send it to the front.

Here is the custom JDialog class I made. 

 
Then just call that from within your JFrame.

The StageModalDialog class is a custom class I made that inherits from the Stage class.

Here is a short code to create a login/password dialog using only JOptionPane. This way, you do not have to waste your time making a custom JDialog class.

Related Posts Plugin for WordPress, Blogger...