Java Reference
In-Depth Information
Directory "Sketcher 4 creating text elements"
This method does something only if the element type is
TEXT
and button 1 was clicked. The dialog for
entering text is displayed using the
showInputDialog()
method. You only want to create an element if
text
is not
null
and not empty. If the dialog Cancel button is selected,
text
is
null
, and
text
is empty
if OK is selected without entering any text.
You obtain a
Graphics2D
object from the view so you can obtain a
FontMetrics
object from the graph-
ics context for the current font. You then create an
Element.Text
object by calling its constructor.
Because you reference the
TEXT
constant here, you must add a static import for the
SketcherConstants
class members to the
SketcherView
class file:
import static Constants.SketcherConstants.*;
You also need to add an import for
javax.swing.JOptionPane
, or you can change the import for
JCom-
ponent
to import all names from the package.
A mouse clicked event occurs when the mouse is pressed and then immediately released. Of course, this
also causes mouse pressed and mouse released events to occur as well. You rely on the
mousePressed()
method to record the
start
point and the button state, but you must prevent this method and the
mousedDragged()
and
mouseReleased()
methods from doing anything else when the element type is
TEXT
. Add the following statement after the statement that records the start point in
mousePressed()
:
public void mousePressed(MouseEvent e) {
start = e.getPoint(); // Save the cursor position
in start
buttonState = e.getButton(); // Record which button was
pressed
if(theApp.getWindow().getElementType() == TEXT) return;
// Rest of the code as before...
}
Directory "Sketcher 4 creating text elements"
The
mouseDragged()
implementation can be:
public void mouseDragged(MouseEvent e) {
last = e.getPoint(); // Save cursor
position
if(theApp.getWindow().getElementType() == TEXT) return;
// Rest of the method code as before...
}