Java Reference
In-Depth Information
If you want the toolbar button as well, you will need to add one statement to the SketchFrame
constructor following the others that add element type selection buttons:
// Add element type buttons
toolBar.addSeparator();
addToolBarButton(lineAction);
addToolBarButton(rectangleAction);
addToolBarButton(circleAction);
addToolBarButton(curveAction);
addToolBarButton(textAction);
The action events for the menu item and toolbar button for text are taken care of and the final piece is
dealing with mouse events when we create a text element.
Text elements are going to be different to shapes in how they are created. To create a text element we
need to know what the text is, its color, its font, and where it is to be placed. We will also have to
construct its bounding rectangle. This sounds as though it might be easier than geometric elements, but
there are complications.
Try It Out - Creating Text Elements
We start the process of creating geometric elements in SketchView 's MouseHandler class, but we
can't simply start with the mousePressed() method, as would at first seem logical. The problem is the
sequence of events. We want to display a dialog to manage the text entry, but if we display a dialog in
the mousePressed() method, the mouseReleased() event will get lost, unless you're happy to hold
down the mouse button while typing into the text field with the other hand! A simple solution is to
separate the creation of text elements altogether, and create them in the mouseClicked() method.
This method is called after the mouse button is released, so all the other events will have occurred and
been dealt with.
We can implement this method in the inner class, MouseHandler , to create a text element along the
following lines:
public void mouseClicked(MouseEvent e) {
if((e.getButton()== MouseEvent.BUTTON1) &&
(theApp.getWindow().getElementType() == TEXT)) {
start = e.getPoint(); // Save cursor position - start of text
String text = JOptionPane.showInputDialog(
(Component)e.getSource(), // Used to get the frame
"Enter Text:", // The message
"Dialog for Text Element", // Dialog title
JOptionPane.PLAIN _ MESSAGE); // No icon
if(text != null && text.length()!=0) { // If we have text
// create the element
// Code to create the Element.Text element
// and add it to the sketch model...
}
}
}
Search WWH ::




Custom Search