Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Feb 4, 2000

Set Browser Window As Parent Of Modal Dialog

Sometimes, it is useful for an applet to launch a modal dialog whose parent is the browser window containing the applet. This is so when we'd like to get some data from a user via a dialog, and we'd like the dialog to always sit on top the browser window.

Before the days of Java plugin, all we had to do was to get the parent of the applet, cast it into a Frame, and set it as parent of the dialog.

 
//somewhere in the applet code 
.... 
Frame parent = ((Frame)this.getParent()); 
Dialog d = new Dialog(parent, true); 
.... 
//rest of the applet code 
This works fine if the applet is viewed from a plain HTML page without the use of plugin. With the java plugin, however, this approach causes a "ClassCastException". The windowing object hierarchy differ from one major browser to the other.

In case of Internet Explorer (IE) 5.0, we have to get the parent of the parent of the parent. In case of Netscape, we have to get the parent of the parent. So, to cover the bases, we have to do something like:

 
If 
  the "parent of the parent of the applet's parent" is not null 
then 
  use it for setting the parent //IE with plugin 
else 
If 
  the "parent of the applet's parent" is not null 
then 
  //Netscape with plugin 
  use it for setting the parent 
else 
  //No plugin/Appletviewer 
  use the applet's parent for setting the parent 
This is a bit awkward, isn't it? Well, now that we know some parent of some child must be a Frame, we can use a recursive function that finds the first parent frame, as in:
 


    public Frame getParentFrame(Component c) 
    { 
         Container cont  = c.getParent(); 
         if (cont instanceof Frame) 
         { 
                 return (Frame) cont; 
         } 
         else 
         { 
                 return getParentFrame((Component) cont); 
         } 
    } 
Then, we can use this function as in:
 
//somewhere in the applet code 
.... 
Frame parent = getParentFrame(this); 
Dialog d = new Dialog(parent, true); 
.... 
//rest of the applet code 
This way, we'll have a generic approach that covers browsers with or without the plugin as well as the appletviewer.
Behrouz Fallahi
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap