Java Reference
In-Depth Information
theApp.getWindow().getElementColor(), // The text color
new java.awt.font.TextLayout(text, font, // The bounding rectangle
g2D.getFontRenderContext()).getBounds().getBounds()
);
if(tempElement != null) { // If we created one
theApp.getModel().add(tempElement); // add it to the model
tempElement = null; // and reset the field
}
g2D.dispose(); // Release context resources
g2D = null;
start = null;
}
The bounding rectangle for the text is produced by the rather fearsome looking expression for the last
argument to the
Element.Text
constructor. It's much easier than it looks so let's take it apart.
The
TextLayout
constructor we are using requires three arguments, the text string, the font, and a
FontRenderContext
object for the context in which the text is to be displayed. We call the
getBounds()
method for the
TextLayout
object, which returns a reference to a rectangle of type
Rectangle2D
. Since we want a rectangle of type
Rectangle
to pass to our
Element.Text
constructor,
we call the
getBounds()
method for the
Rectangle2D
object, hence the repetition in the code.
Once the element has been created, we just add it to the model, and clean up the variables that we
were using.
We must now make sure that the other mouse event handlers do nothing when the current element is
TEXT
.
We don't want the
XOR
mode set when we are just creating text elements for instance. A simple additional
condition that tests the current element type will take care of it in the
mousePressed()
method:
public void mousePressed(MouseEvent e) {
// Code to handle mouse button press...
if((button1Down = (e.getButton()==MouseEvent.BUTTON1)) &&
(theApp.getWindow().getElementType() != TEXT)) {
start = e.getPoint(); // Save the cursor position in start
g2D = (Graphics2D)getGraphics(); // Get graphics context
g2D.setXORMode(getBackground()); // Set XOR mode
g2D.setPaint(theApp.getWindow().getElementColor()); // Set color
}
}
The
if
expression will only be
true
if button 1 was pressed and the current element type is not
TEXT
.
We can update the
mouseDragged()
method in a similar way:
public void mouseDragged(MouseEvent e) {
last = e.getPoint(); // Save cursor position
if(button1Down && (theApp.getWindow().getElementType() != TEXT)) {
if(tempElement == null) // Is there an element?
tempElement = createElement(start, last); // No, so create one