Java Reference
In-Depth Information
A DVANCED T OPIC 2.2: Applets
In the preceding section, you learned how to write a program that displays graphical
shapes. Some people prefer to use applets for learning about graphics programming.
Applets have two advantages. They don't need separate component and viewer
classes; you only implement a single class. And, more importantly, applets run
inside a web browser, allowing you to place your creations on a web page for all the
world to admire.
Applets are programs that run inside a web browser.
To implement an applet, use this code outline:
public class MyApplet extends JApplet
{
public void paint(Graphics g)
{
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g;
// Drawing instructions go here
. . .
}
}
This is almost the same outline as for a component, with two minor differences:
1. You extend JApplet , not JComponent .
2. You place the drawing code inside the paint method, not inside
paintComponent .
The following applet draws two rectangles:
ch02/applet/RectangleApplet.java
1 import java.awt.Graphics;
2 import java.awt.Graphics2D;
3 import java.awt.Rectangle;
4 import javax.swing.JApplet;
5
Search WWH ::




Custom Search