Launching a Frame from an Applet

   

How do I create an AWT applet that opens a frame when I press an applet button, and then closes the frame when I press a frame button?

In the applet's init method, you construct a GUI consisting of a single button. You then register an object to listen for button press events. When such an event occurs, you create and display a frame.

The frame is created with its own button that, when pressed, closes the frame. This is accomplished by registering an object that listens for press events from this button. In response, the listener calls the dispose method (inherited from Frame 's Window class parent) to close the frame. The following MyApplet3 applet demonstrates this technique.

 // MyApplet3.java import java.awt.*; import java.awt.event.*; public class MyApplet3 extends java.applet.Applet                        implements ActionListener {    Button b;    public void init ()    {       b = new Button ("Open frame");       b.addActionListener (this);       add (b);    }    public void actionPerformed (ActionEvent e)    {       b.setEnabled (false);       new MyFrame ("MyFrame", b);    } } class MyFrame extends Frame implements ActionListener {    private Button launch;    MyFrame (String title, Button launch)    {       super (title);       // Assign launch argument to launch field.       this.launch = launch;       Button b = new Button ("Close Frame");       b.addActionListener (this);       Panel p = new Panel ();       p.add (b);       add (p);       setSize (200, 80);       setVisible (true);    }    public void actionPerformed (ActionEvent e)    {       dispose ();       launch.setEnabled (true);    } } 

If you would like to launch multiple frames , comment out the b.setEnabled (false) method call (in MyApplet3 's actionPerformed method) and the launch.setEnabled (true) method call (in MyFrame 's actionPerformed method). These two method calls are responsible for disabling the button prior to launching a frame, and enabling the button after disposing this frame. As a result, these method calls ensure that only one frame is launched at a time.

Why would you want to launch a frame from an applet? Suppose you need to construct an image gallery applet. You have a complex GUI that you want to display in the applet's display area, but you also need to be able to display images of various sizes. Instead of trying to figure out appropriate sizes for the <APPLET> tag's WIDTH and HEIGHT attributes, you could choose to display the GUI (minus the image) in the display area, and the image in a frame that is displayed from this GUI. Each time the frame is displayed, it might be given a new size, to match the size of the image it's displaying.

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net