Java Reference
In-Depth Information
public class RectangleComponent extends JComponent
{
public void paintComponent(Graphics g)
{
// Recover Graphics2D
Graphics2D g2 = (Graphics2D) g ;
. . .
}
}
Now you are ready to draw shapes. The draw method of the Graphics2D class can
draw shapes, such as rectangles, ellipses, line segments, polygons, and arcs. Here we
draw a rectangle:
public class RectangleComponent extends JComponent
{
public void paintComponent(Graphics g)
{
. . .
Rectangle box = new Rectangle(5, 10, 20,
30);
g2.draw (box);
. . .
}
}
Following is the source code for the RectangleComponent class. Note that the
paintComponent method of the RectangleComponent class draws two
rectangles.
As you can see from the import statements, the Graphics and Graphics2D
classes are part of the java.awt package.
ch02/rectangles/RectangleComponent.java
1 import java.awt.Graphics;
2 import java.awt.Graphics2D;
3 import java.awt.Rectangle;
4 import javax.swing.JComponent;
5
6 /**
7 A component that draws two rectangles.
Search WWH ::




Custom Search