Java Reference
In-Depth Information
It's now quite a lot shorter as the element sets its own color in the graphics context and we don't need to store
the reference to the element within the loop. We are ready to get back to the Element.Text class.
We must not forget to update the mouseDragged() method in the MouseHandler class in
SketchView to use the new mechanism for drawing elements:
public void mouseDragged(MouseEvent e) {
last = e.getPoint(); // Save cursor position
if(button1Down) {
if(tempElement == null) // Is there an element?
tempElement = createElement(start, last); // No, so create one
else {
tempElement.draw(g2D); // Yes - draw to erase it
tempElement.modify(start, last); // Now modify it
}
tempElement.draw(g2D); // and draw it
}
}
We can define the Element.Text class quite easily now. We will need five arguments for the constructor
though - the font to be used for the string, the string to be displayed, the position where it is to be displayed,
its color, and its bounding rectangle. To get a bounding rectangle for a string, we need access to a graphics
context, so it will be easier to create the bounding rectangle before we create a text element.
Here's the class definition:
class Element {
// Code that defines the base class...
// Definitions for the other shape classes...
// Class defining text element
public static class Text extends Element {
public Text(Font font, String text, Point position, Color color,
java.awt.Rectangle bounds) {
super(color);
this.font = font;
this.position = position;
this.text = text;
this.bounds = bounds;
this.bounds.setLocation(position.x, position.y - (int)bounds.getHeight());
}
public java.awt.Rectangle getBounds() {
return bounds;
}
public void draw(Graphics2D g2D) {
g2D.setPaint(color);
Font oldFont = g2D.getFont(); // Save the old font
g2D.setFont(font); // Set the new font
g2D.drawString(text, position.x, position.y);
Search WWH ::




Custom Search