Java Reference
In-Depth Information
Try It Out - Defining the Element.Text Class
Let's see how that works out. We can start by adding an abstract method, draw() to the Element
class definition:
public abstract class Element {
public Element(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
public abstract java.awt.Rectangle getBounds();
public abstract void modify(Point start, Point last);
public abstract void draw(Graphics2D g2D);
protected Color color; // Color of a shape
// Plus definitions for our shape classes...
}
Note that we have deleted the getShape() method as we won't be needing it further. You can remove
it from all the nested classes of the Element class. The draw() method now needs to be implemented
in each of the nested classes to the Element class, but because each of the current classes has a Shape
member, it will be essentially the same in each. The version for the Element.Line class will be:
public void draw(Graphics2D g2D) {
g2D.setPaint(color); // Set the line color
g2D.draw(line); // Draw the line
}
This just sets the color and passes the Shape object that is a member of the class to the draw() method
for the Graphics2D object. To implement the draw() method for the other element classes, just
replace the argument to the g2D.draw() method call, with the name of the Shape member of the
class, and update the comments. You also need to make the Graphics2D class accessible so add an
import statement for it to Element.java :
import java.awt.Graphics2D;
You can now change the implementation of the paint() method in the SketchView class to:
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D)g; // Get a 2D device context
Iterator elements = theApp.getModel().getIterator();
while(elements.hasNext()) // Go through the list
((Element)elements.next()).draw(g2D); // Get the next element to draw
// itself
}
Search WWH ::




Custom Search