Java Reference
In-Depth Information
•
repaint(int msec, int x,int y,int width, int height)
adds the region specified by
the arguments to the dirty region list if the component is visible. The
dirty region list
is simply
a list of areas of the component that need to be repainted. The component is repainted by calling
its
paint()
method when all currently outstanding events have been processed, or within
msec
milliseconds. The region is the rectangle at position (
x
,
y
), with the width and height as specified
by the last two arguments.
•
repaint(Rectangle rect)
adds the rectangle specified by
rect
to the dirty region list if the
component is visible. The dirty region is the area to be repainted when the component is next re-
drawn.
You will find that the first and the last methods are the ones you use most of the time.
That's enough theory for now. It's time to get a bit of practice. Let's get an idea of how you can draw
on a component by drawing on the
SketcherView
object that you added to Sketcher. All you need to do is
implement the
paint()
method in the
SketcherView
class that you added earlier in this chapter.
TRY IT OUT: Drawing in a View
You are going to modify Sketcher temporarily to make it display a 3D rectangle. Add the following im-
plementation of the
paint()
method to the
SketcherView
class:
import javax.swing.JComponent;
import java.util.*;
import java.awt.*;
class SketcherView extends JComponent implements Observer {
// Method to draw on the view
@Override
public void paint(Graphics g) {
// Temporary code to be replaced later...
Graphics2D g2D = (Graphics2D)g;
// Get a Java 2D
device context
g2D.setPaint(Color.RED);
// Draw in red
g2D.draw3DRect(50, 50, 150, 100, true);
// Draw a raised
3D rectangle
g2D.drawString("A nice 3D rectangle", 60, 100); // Draw some text
}
// Rest of the class as before...
}
Directory "Sketcher 1 drawing a 3D rectangle"
If you recompile the
SketcherFrame.java
file and run Sketcher once again, you can see what the
paint()
method produces. You should see the window shown in
Figure 19-5
.