Creating a new frame window from within an applet is actually quite easy. First, create
a subclass of Frame. Next, override any of the standard applet methods, such as init( ), start( ),
and stop( ), to show or hide the frame as needed. Finally, implement the windowClosing( )
method of the WindowListener interface, calling setVisible(false) when the window is closed.
Once you have defined a Frame subclass, you can create an object of that class. This causes
a frame window to come into existence, but it will not be initially visible. You make it visible
by calling setVisible( ). When created, the window is given a default height and width. You
can set the size of the window explicitly by calling the setSize( ) method.
The following applet creates a subclass of Frame called SampleFrame. A window of this
subclass is instantiated within the init( ) method of AppletFrame. Notice that SampleFrame
calls Frame's constructor. This causes a standard frame window to be created with the title
passed in title. This example overrides the applet's start( ) and stop( ) methods so that they
show and hide the child window, respectively. This causes the window to be removed
automatically when you terminate the applet, when you close the window, or, if using a
browser, when you move to another page. It also causes the child window to be shown when
the browser returns to the applet.
//  Create a child frame window from within an applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletFrame" width=300 height=50>
</applet>
*/
// Create a subclass of Frame.
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString("This is in frame window", 10, 40);
}
}
class MyWindowAdapter extends WindowAdapter {
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame) {
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we) {
sampleFrame.setVisible(false);
}
}
// Create frame window.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home