Java Reference
In-Depth Information
Handling Button Release Events
When the mouse button is released, you have created an element. In this case all you need to do is to add the
element that is referenced by the
tempElement
member of the
MouseHandler
class to the
SketcherModel
object that represents the sketch. One thing you need to consider, though: someone might click the mouse
button without dragging it. In this case there won't be an element to store. In this case you just clean up the
data members of the
MouseHandler
object:
public void mouseReleased(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
buttonState = MouseEvent.NOBUTTON;
// Reset the button state
if(tempElement != null) { // If there is an element...
theApp.getModel().add(tempElement); // ...add it to the model...
tempElement = null;
// ...and reset the field
}
if(g2D != null) {
// If there's a graphics context
g2D.dispose();
// ...release the resource...
g2D = null;
// ...and reset field to null
}
start = last = null;
// Remove any points
}
}
Directory "Sketcher 4 drawing sketch line and rectangle elements"
When button 1 for the mouse is released it changes state, so you can use the
getButton()
method here
to verify that this occurred. Of course, once button 1 is released, you should reset
buttonState
.
If there is a reference stored in
tempElement
, you add it to the model by calling the
add()
method that
you defined for the
SketcherModel
class and set
tempElement
back to
null
. It is most important that you
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.
Another important operation that the
mouseReleased()
method carries out is to call the
dispose()
method for the
g2D
object. Every graphics context makes use of system resources. If you use a lot of graphics
context objects and you don't release the resources they use, your program consumes more and more re-
sources. When you call
dispose()
for a graphics context object, it can no longer be used, so you set
g2D
back to
null
to be on the safe side.
When you add the new element to the model, the view is notified as an observer, so the
update()
method
for the view object is called. You can implement the
update()
method in the
SketcherView
class like this:
public void update(Observable o, Object rectangle) {
if(rectangle != null) {
repaint((Rectangle)rectangle);