google search

Tuesday, April 13, 2010

CREATING A FRAME WINDOW IN APPLET

While it is possible to simply create a window by creating an instance of Frame, you
will seldom do so, because you will not be able to do much with it. For example, you
will not be able to receive or process events that occur within it or easily output
information to it. Most of the time, you will create a subclass of Frame. Doing so lets
you override Frame’s methods and event handling.
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 window methods, such as init( ),
start( ), stop( ), and paint( ). 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 window’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.*;
/*


*/
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
MyWindowAdapter adapter = new MyWindowAdapter(this);

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);
}
}
public class AppletFrame extends Applet {
Frame f;
public void init() {
f = new SampleFrame("A Frame Window");
f.setSize(250, 250);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
public void paint(Graphics g) {
g.drawString("This is in applet window", 10, 20);
}
}

0 comments:

  © Blogger templates ProBlogger Template by Ourblogtemplates.com 2008

Back to TOP