Java Reference
In-Depth Information
Creating Text Elements
Text is a little tricky. For one thing, you can't treat it just like another geometric element. The mouse won't
be used in the same way. The existing process for creating shapes through the mouse event handlers has to
be changed to accommodate text. Basically, the process for creating an element when text mode is in effect
is to click the mouse to set the location for the text and then enter the string that is to be displayed through a
dialog. This suggests that implementing the mouseClicked() event handler may be a good way to go. The
mouseClicked() handler is only invoked when button 1 is pressed then released. It is not called if you drag
the mouse between pressing and releasing button 1.
TRY IT OUT: Creating Text Elements
The mouseClicked() method in the WindowHandler inner class to SketcherView creates Text ele-
ments:
@Override
public void mouseClicked(MouseEvent e) {
// Only if it's TEXT and button 1 was clicked
if(theApp.getWindow().getElementType() == TEXT &&
buttonState ==
MouseEvent.BUTTON1) {
String text = JOptionPane.showInputDialog(
theApp.getWindow(),"Enter Input:",
"Create Text Element",
JOptionPane.PLAIN_MESSAGE);
if(text != null && !text.isEmpty()) {
// Only if text
was entered
g2D = (Graphics2D)getGraphics();
tempElement = new Element.Text(text, start,
theApp.getWindow().getElementColor(),
g2D.getFontMetrics(theApp.getWindow().getFont()));
g2D.dispose();
g2D = null;
if(tempElement != null) {
theApp.getModel().add(tempElement);
}
}
tempElement = null;
// Reset for next
element creation
start = null;
// Reset for next element
}
}
Search WWH ::




Custom Search