Java Reference
In-Depth Information
if(buttonState == MouseEvent.BUTTON1 && mode == NORMAL) {
g2D = (Graphics2D)getGraphics(); // Get graphics
context
g2D.setXORMode(getBackground()); // Set XOR mode
}
}
Directory "Sketcher 10 moving and rotating elements"
It's only necessary to verify that the sketching mode is
NORMAL
and button 1 is down before you set
XOR
mode. You may wonder why it is not necessary to use the
equals()
method to compare
mode
with
NORMAL
. You should use
equals()
to compare arbitrary strings but here,
mode
is not arbitrary. It can only
be a reference to one of the
String
objects you defined in the
SketcherConstants
class. This allows
you to compare the
String
references for equality.
You have to test for the setting of
mode
in the
mouseDragged()
method, and execute different code de-
pending on its value. You have three possibilities:
NORMAL
, where you do as you did before;
MOVE
, where
you execute a move operation; and
ROTATE
, where you execute a rotate operation, which you implement
later. Here's the new version of
mouseDragged()
to accommodate moving elements:
public void mouseDragged(MouseEvent e) {
last = e.getPoint(); // Save cursor
position
if(theApp.getWindow().getElementType() == TEXT && mode ==
NORMAL) return;
// Select operation based on sketching mode
switch(mode){
case NORMAL:
// Creating an element
if(buttonState == MouseEvent.BUTTON1) {
if(tempElement == null) { // Is there an
element?
tempElement = Element.createElement( // No, so create
one
theApp.getWindow().getElementType(),
theApp.getWindow().getElementColor(),
start, last);
} else {
tempElement.draw(g2D); // Yes - draw to
erase it
tempElement.modify(start, last); // Now modify it
}
tempElement.draw(g2D); // and draw it
}
break;