Java Reference
In-Depth Information
AffineTransform old = g2D.getTransform(); // Save the current transform
g2D.translate(position.x, position.y); // Translate to position
g2D.drawString(text, origin.x, origin.y+(int)bounds.getHeight());
g2D.setTransform(old); // Restore original transform
g2D.setFont(oldFont); // Restore the old font
}
The transformation applied in the draw() method here is essentially the same as for the other classes.
We now add the height of the bounding rectangle to the y coordinate of position in the argument to
drawString() . This specifies the bottom-left corner of the first text character.
You can now recompile Sketcher for another trial. If you have done everything right it should still work
as before.
How It Works
All the classes defining elements create the elements at the origin, and store their location in a member,
position , that is inherited from the base class, Element . 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 untransformed coordinate system, because that is the
context in which we shall be using it. We are now ready to try moving elements around.
Moving an Element
Now we can implement the Move operation that we 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. We can add a move()
method to the base class, Element , that will move any element, and it is just two lines of code:
public void move(int deltax, int deltay) {
position.x += deltax;
position.y += deltay;
}
Let's review the process that we will implement to make a move. From a user point of view, to move an
element you just click on the Move menu item, then drag the highlighted element to where you want it
to be with button 1 held down.
In programming terms a move will be initiated in the actionPerformed() method in SketchView
that responds to a menu selection. When the Move menu item is clicked, we will set the operating mode
to what we will define as MOVE mode, so that we can detect this in the mouse handler methods that will
expedite a move. The Rotate menu will work in exactly the same way, setting a ROTATE mode. To
accommodate this we will add a member, mode , of type int , to store the current operating mode. By
default, it will be NORMAL .
Search WWH ::




Custom Search