Java Reference
In-Depth Information
else {
g2D.draw(tempElement.getShape()); // Yes - draw to erase it
tempElement.modify(start, last); // Now modify it
}
g2D.draw(tempElement.getShape()); // and draw it
}
}
We have also updated the statements that draw an element to call the new method in the element
classes. The change to the
mouseReleased()
method is exactly the same as for
mousePressed()
so
let's go ahead and modify the
if
condition. The only other change we need to make is to make the
status bar respond to the
TEXT
element type being set. To do this we just need to make a small addition
to the definition of the
setTypePane()
method in the
StatusBar
class:
public void setTypePane(int elementType) {
String text; // Text for the type pane
switch(elementType) {
// case label as before...
case TEXT:
text = "TEXT";
break;
default:
assert false;
}
typePane.setText(text); // Set the pane text
}
How It Works
The
mouseClicked()
handler responds to mouse button 1 being clicked when the element type is
TEXT
. This method will be called after the
mouseReleased()
method. Within the
if
statement that
determines this, we create a dialog to receive the text input by calling the static
showInputDialog()
in the
JOptionPane
class. If you selected the
Cancel
button in the dialog, text will be
null
so in this
case we do nothing. If text is not
null
, we create an
Element.Text
object at the current cursor
position containing the text string that was entered in the dialog. We then add this to the model, as long
as it's not
null
. It is important to remember to reset the
start
and
tempElement
members back to
null
, so as not to confuse subsequent event handling operations.
Incidentally, although there isn't a method to detect double-clicks on the mouse button, it's easy to
implement. The
getClickCount()
method for the
MouseEvent
object that is passed to
mouseClicked()
returns the click count. To respond to a double-click you would write:
if(e.getClickCount() == 2) {
//Response to double-click...
}
The other event handling methods behave as before so far as the geometric elements are concerned,
and do nothing if the element type is
TEXT
. We can try it out.