Java Reference
In-Depth Information
We will need to import
JOptionPane
from
javax.swing
into
SketchView.java
so add the import:
import javax.swing.JOptionPane;
We only want to do something here if it was mouse button 1 that was clicked and the current element
type is
TEXT
. In this case we save the cursor position and pop a dialog to permit the text string to be
entered. If there was one that is not an empty string, we go ahead and create a text element and add it
to the sketch model.
We still have to add the code for creating a text element. The tricky part is figuring out what the
rectangle bounding the text is. The
Font
class defines a
getStringBounds()
method that returns a
rectangle bounding a string in a given context in which the string is drawn. Unfortunately, as the
documentation for this method says, it does not always return a rectangle enclosing all of the text. To
get a rectangle that completely encloses the text in every case we must create a
TextLayout
object for
the text and call its
getBounds()
method.
This
TextLayout
class is defined in the
java.awt.font
package so we will need an import
statement for that in the
SketchView.java
file:
import java.awt.font.TextLayout;
A
TextLayout
object encapsulates the graphical representation of a given text string on a particular
graphics device so, as well as the text and the font, a
TextLayout
class constructor needs information
on the dimensions of the font in the context of the graphical device. The
FontRenderContext
class in
the
java.awt.font
package defines an object encapsulating the information necessary to display text
in a given graphics context. You can obtain a
FontRenderContext
object from a
Graphics2D
object,
g2D
, like this:
FontRenderContext frc = g2D.getFontRenderContext();
All we need now is a
Graphics2D
object. We can get that using the
getGraphics()
method that our
SketchView
object inherits from the
JComponent
class:
Graphics2D g2D = (Graphics2D)getGraphics();
We have all the pieces we need to create the bounding rectangle for the text, and hence the
Element.Text
object. Here's the code that goes in the
if
statement that will create the text element
and add it to the model:
if(text != null) { // If we have text
// create the element
g2D = (Graphics2D)getGraphics();
Font font = theApp.getWindow().getCurrentFont();
tempElement = new Element.Text(
font, // The font
text, // The text
start, // Position of the text