How can I display a modal Dialog from an applet in the Browser?

Finlay McWalter

In order to display a Dialog, you need a Frame to be the "owner" of the dialog - all of the java.awt.Dialog constructors require a Frame. Now, I've seen several "teach yourself java" books that say you should make a dummy Frame, and then pass that in as the parent - but that's plain silly.

What you need to do is walk up the AWT widget instance heirarchy (walking upward from the applet) - at the top of such heirarchies you'll find a Window, a Dialog or a Frame (the three "toplevel" widgets in AWT) - thoughtfully the applet host code will always set itself up as a Frame, just so you can use that as a parent for your dialogs. This walkup procedure is shown in the following example - it's done in the findParentFrame() method.

import java.awt.*; 
import java.awt.event.*; 
import java.applet.Applet; 

public class test extends Applet implements ActionListener { 
  Button b; 

  private Frame findParentFrame(){ 
    Container c = this; 
    while(c != null){ 
      if (c instanceof Frame) 
        return (Frame)c; 

      c = c.getParent(); 
    return (Frame)null; 

  public void init(){ 
    setLayout(new FlowLayout()); 
    b = new Button("push me"); 

  public void actionPerformed(ActionEvent e){ 
    Frame f = findParentFrame(); 
    if(f != null){ 
      Dialog d = new Dialog(f, "modalDialog", true); 
      d.setLayout(new FlowLayout()); 
      d.add(new Label("hello")); 

So that's that, right?

Well, not entirely. As with many aspects of their implementation of Java applets, browsers differ in how they interpret the meaning of "modal". Almost all make the dialog modal with respect to the applet that created it, but some make it fully modal (i.e. the entire browser is waiting on the modal dialog) and others allow other browser windows or even the same browser window (perhaps with other Java applets in it) to continue to run. This seems to happen more because of the way browser vendors implement the event handling loops in their products than by deliberate design (one major browser manufacturer we could name varies in this regard between the same browser on different OSes). Short of scary JavaScript/LiveConnect/JNI nastiness, you'll have to live with your browser manufacturer's conception of how to implement modal.

For browser manufacturers, ignoring modal behaviour for applets is often a wise choice - otherwise, malicious or defective applets (um, like my example above) can bring up a modal dialog with no means of it being closed, and thus leave the entire browser unusable - forcing the user to kill the browser to recover.

Another small note about modal dialogs - if you intend your applet to work on Personal Java platforms (things like cable-boxes and webphones) you should assume that only modal dialogs are permitted - Personal Java allows the browser to throw an exception if the browser doesn't support non-modal dialogs.