DrawingGraphics
The applet's real estate is the area within the border
Source
AnAppletWithGraphics.java:
import java.applet.*;
import java.awt.*;
public class AnAppletWithGraphics extends Applet {
public void paint(Graphics g) {
g.drawLine(0, 0, 100, 100);
g.setColor(Color.green);
g.drawRect(10, 30, 20, 60);
g.setColor(new Color(100, 50, 210));
g.fillOval(20, 10, 15, 30);
g.setColor(Color.red);
g.drawString("Hi There!", 25, 55);
}
}
Description and Objective
The AnAppletWithGraphics
class
- Illustrates how to draw graphic shapes in an applet
- How to set the color when drawing graphics
Notes
Drawing Graphics
- Graphic shapes may be drawn when the
paint
method is invoked
- Most drawing within the context of
paint
requires the use of the Graphics
object
passed as a parameter to paint
- The
Graphics
object also allows you to set the current foreground color
- Text is considered a graphic in the system, and thus text may be drawn as well using the
drawString
methods of the Graphics
object
This Applet's Behavior
- This applet has no instance variables to initialize and requires no other initialization behavior, so no
init
method
is provided.
- The
paint
method draws several shapes (including text) in several colors onto the applet's surface.
- The
setColor
method is used to change the 'pen'/'foreground' color.
- Once set, the color remains only again changed
- Note: While the foreground color requires a method (i.e.,
setColor
) invoked on the Graphics
parameter, the backgeound color is set using a method (setBackground
) of the Applet
class itself.
Color
constants as well as custom colors are used.
- The
drawRect
draws an outline of a rectangle in the current color,
while the fillRect
draws a rectangle whose interior is filled in with the color.
Things to Do
API work
- The
Graphics
class
- Which package is it in?
- Find the various methods used
- What other useful drawing methods can you find?
Playing with the Applet
Place the following applets on the same page:
- Code an applet that draws a smiley face
- Code an applet that accepts two integer parameters.
- The first, named quantity (assume it will be no more than 4) determines the
number of circles to draw. The circles should be drawn adjacent to each other, touching at the single point.
- The second parameter is the diameter of each circle.
- Introduce an
init
method and some instance variables to hold the values of the parameters
- Same as #1, but now, have the face toggle between a smiley and a frown with each invocation of
paint