SCJP Java Programming Exam Cram Notes : java Painting.

2. Selecting a Font - g.setFont(Font)

A Font is created by Font(String name, int style, int size)

3. Drawing and Filling - Various draw, fill methods

4. Clipping - g.setClip(Shape) or g.setClip(x, y, width, height)

Graphics class is an abstract class. It cannot be created. But an instance can be obtained in 2 ways.

1. Every component has an associated graphics context. Get this using getGraphics method.

2. Given an existing Graphics object, call create() on that object to create a new one.

In both cases, after its use call dispose method on Graphics, to free the resources. We shouldn't call dispose on the graphics context passed into paint() method, since it's just temporarily made available.

JVM calls paint() spontaneously under 4 circumstances

1. After exposure

2. After de-iconification

3. Shortly after init returns (Applets only)

4. Browser returns to a page contains the Applet (Applets only)

In all cases, clip region is set appropriately. If only a small portion is exposed, no time is wasted in drawing already drawn pixels.

Programs can also call paint(). But normally they achieve this by calling repaint(). Repaint() schedules a call to update() method (every 100 ms in most platforms). This is to ensure that JVM is never overwhelmed with the events.

update() restores the component's background color and calls paint(). If you don't want to erase the previously drawn content, override update() and just call paint() from it. (A common practice).

Event handlers that need to modify the screen according to input events, usually store the state information in instance variables and call repaint().

Images can be created from empty (using createImage(int width, int height) method) or loaded from external image files (using getImage() method in Toolkit class). Then they can be modified using the graphics context associated with the image. They can be drawn on the component using the drawImage method of the Graphics context of the component.

Previous    Contents    Next