"Appletcations"

Download Report

Transcript "Appletcations"

"Appletcations"
Applets and applications
You create an applet by extending Applet
You may, but are not required to, override
methods of Applet: init, start, paint, stop,
destroy
An application requires a public static void
main(String args[]) method
You can create an "appletcation" by simply
doing all of the above
Hello1.java
import java.awt.*;
import java.applet.Applet;
public class Hello1 extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 30, 30);
}
}
Hello1.html
<applet code="Hello1.class"
width="250"
height="100">
</applet>
I won't bother showing the HTML after this
Hello2.java
public static void main(String args[]) {
Frame myFrame = new Frame("Hello2");
Applet myApplet = new Hello2( );
myFrame.add(myApplet,
BorderLayout.CENTER);
myFrame.setSize(250, 100);
myApplet.init( );
myApplet.start( );
myFrame.setVisible(true);
}
Closing
Hello2.java works fine, but...
...You can't close the window by clicking the x in
the upper-right corner; you have to use Ctrl-C
You can fix this by adding implementing
WindowListener; or better yet, by extending
WindowAdapter
Hello3.java
import java.awt.event.*;
Add to main:
myFrame.addWindowListener(new myCloser());
New class:
class myCloser extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}
Adding stop( ) and destroy( )
Applets sometimes (but rarely) use stop( ) and
destroy( )
These should be called in windowClosing( )
To do this, windowClosing( ) must have access to
the Applet's methods, hence to the Applet itself
The Applet can be made a static member of its
own class
Hello4.java
public class Hello4 extends Applet {
// myApplet has been moved and made static:
static Applet myApplet = new Hello4( );
public void windowClosing(WindowEvent event) {
Hello4.myApplet.stop( );
//new
Hello4.myApplet.destroy( );
//new
System.exit(0);
}
Debugging (and other) output
Applications can use System.out.println(String
message)
This also works for applets run from appletviewer,
but not if they are run from a browser
Applets can use showStatus(String message)
If you do this from an application, you must supply
an AppletContext, or you get a nullPointerException
You can always use drawString( ), or better, a
TextField
Hello5.java
public void paint(Graphics g) {
g.drawString("Hello World!", 30, 30);
showStatus("OK for applets");
System.out.println("OK for applications");
g.drawString("OK for both applets " +
" and applications", 10, 50);
}
The End