Java Reference
In-Depth Information
public int getElementType() {
return elementType;
}
The switch statement in createElement() selects the constructor to be called, and as you see, they
are all essentially of the same form. If we fall through the switch with an ID that we haven't provided
for, we return null . Of course, none of these shape class constructors exists in Sketcher yet. So if you
want to try compiling the code we have so far, you will need to comment out each of the return
statements. The constructor calls imply that all our shape classes are inner classes to the Element class.
We will see how to implement these very soon. But first, let's add the next piece of mouse event
handling we need - handling button release events.
Handling Button Release Events
When the mouse button is released, we will have created an element. In this case all we need to do is to
add the element referred to by the tempElement member of the MouseHandler class to the
SketchModel object that represents the sketch. One thing we need to consider though. Someone
might click the mouse button without dragging it. In this case there won't be an element to store, so we
just clean up the data members of the MouseHandler object.
public void mouseReleased(MouseEvent e) {
if(button1Down = (e.getButton()==MouseEvent.BUTTON1)) {
button1Down = false; // Reset the button 1 flag
if(tempElement != null) {
theApp.getModel().add(tempElement); // Add element to the model
tempElement = null; // No temporary now stored
}
if(g2D != null) { // If there's a graphics context
g2D.dispose(); // ...release the resource
g2D = null; // Set field to null
}
start = last = null; // Remove the points
}
}
When the button1 is released it will change state so we can use the getButton() method here. Of
course, once button 1 is released we need to reset our flag, button1Down . If there is a reference stored
in tempElement we add it to the model by calling the add() method that we defined for it and set
tempElement back to null . It is important to set tempElement back to null here. Failing to do that
would result in the old element reference being added to the model when you click the mouse button.
When we add the new element to the model, the view will be notified as an observer, so the update()
method in the view will be called. We can implement the update() method in the SketchView
class like this:
public void update(Observable o, Object rectangle) {
if(rectangle == null)
repaint();
else
Search WWH ::




Custom Search