Java Reference
In-Depth Information
TRY IT OUT: Using Affine Transforms in Drawing Opera-
tions
You can now recompile Sketcher for another trial. If you have done everything right it should still work
as before.
How It Works
The draw methods all apply a transform to move the coordinate system to the point stored in position
before drawing the element. The draw() methods then restore the original transform to leave the graphics
context unchanged. Each of the getBounds() methods returns a bounding rectangle in the original un-
transformed coordinate system, because that is the context in which it is used. You are now ready to try
moving elements around.
Moving Elements
Now you can implement the move operation that you provided for in the context menu. Taking the trouble
to define all the elements relative to the origin and using a transform to position them correctly really pays
off when you want to apply other transformations to the elements. You can add a move() method to the base
class Element that moves any element:
// Move an element
public void move(int deltaX, int deltaY) {
position.translate(deltaX, deltaY);
bounds.translate(deltaX, deltaY);
}
Directory "Sketcher 10 moving and rotating elements"
This makes use of the translate() methods that the Point and Rectangle classes define, which con-
veniently moves the x and y coordinates of a point or rectangle by the increments supplied as the arguments.
When an element is moved, the bounding rectangle must move with it. The transform in the graphics context
makes sure the element is drawn at the right position.
Let's review the process that you are implementing to move an element. From a user's point of view, to
move an element you just click on the Move menu item in the context menu and then drag the highlighted
element to where you want it to be with button 1 held down.
In programming terms, moving an element is initiated in the actionPerformed() method in the an-
onymous class that defines the listener for the Move menu item selection. When the Move menu item is
clicked, you set the Sketcher operating mode to what you define as MOVE mode. You can check for this in the
mouse handler methods that expedite a move. The Rotate menu operation works in exactly the same way
by setting the mode to ROTATE . To accommodate this you add a new member, mode , of type String to the
SketcherView class that stores the current operating mode. You could use type int , but let's use strings to
be different. By default, the mode is NORMAL .
Search WWH ::




Custom Search