Java Reference
In-Depth Information
paint directly; instead, the system calls paint whenever it has to redraw the
window —e.g. when the window is brought to the front or when it is moved.
Second, procedure paint has a parameter g of class Graphics . The instance of
class Graphics that is passed as an argument to paint contains the methods that
draw in the window.
Look at the body of paint . The first statement calls procedure g.setColor ,
with argument . Class Color contains several constants, like , that represent various colors. Execution of this call sets the color of
the pen so that anything drawn after this will be red. In the picture shown above,
the part of the circle that is showing would be red on your monitor.
The second procedure call draws an oval that will fit in the square whose
upper left corner is pixel (0, 0) —given by the first two arguments— and whose
width and height are both 40 (the second two arguments). Pixel (0, 0) is the ori-
gin of the window: its upper left corner. Half of the oval that was drawn is hid-
den by the title bar of the window.
We can change the origin by calling method g.translate . For example,
execution of the following statement moves the origin to the right 20 pixels and
down 30 pixels:
Activity 1-5.5
explains pixels
and talks about
the resolution
of a monitor.
g.translate(20, 30);
Better yet, we can change the origin to the pixel right under the title bar by exe-
cuting this procedure call —the two arguments yield the correct number of pix-
els to move:
If we insert this call as the first statement of method paint and create and
show an instance of class GraphicsFrame , the window will look like this:
import javax.swing.*;
import java.awt.*;
public class GraphicsFrame extends JFrame {
/** Draw a figure in the window accessed by g */
public void paint(Graphics g) {
g.drawOval(0, 0, 40, 40);
Figure 1.12:
Subclass of JFrame with a method paint
Search WWH ::

Custom Search