Java Reference
In-Depth Information
The graphics context also maintains other information necessary for drawing operations such as the
drawing color, the line style and the specification of the fill color and pattern for filled shapes. We will
see how to work with these attributes in examples later in this chapter.
Since a graphics context defines the drawing context for a specific component, before you can draw on a
component you must have a reference to its graphics context object. For the most part, you will draw on a
component by implementing the paint() method that is called whenever the component needs to be
reconstructed. An object representing the graphics context for the component is passed as an argument to the
paint() method, and you use this to do the drawing. The graphics context includes all the methods that
you use to draw on a component and we will be looking into many of these in this chapter.
The paint() method is not the only way of drawing on a component. You can obtain a graphics
context for a component at any time just by calling its getGraphics() method.
There are occasions when you want to get a component redrawn while avoiding a direct call of the
paint() m ethod. In such cases you should call repaint() for the component. There are five
versions of this method that you can use; we'll look at four:
repaint() Method
Description
repaint()
Causes the entire component to be repainted by calling its
paint() method after all of the currently outstanding
events have been processed.
repaint(long msec)
Requests that the entire component is repainted within msec
milliseconds.
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 will be 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.
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. Time to get a bit of practice.
Let's get an idea of how we can draw on a component by drawing on the SketchView object that we
added to Sketcher. All we need to do is implement the paint() method in the SketchView class.
Try It Out - Drawing in a View
Add the following implementation of the method to the SketchView class:
import javax.swing.JComponent;
import java.util.Observer;
Search WWH ::




Custom Search