Java Reference
In-Depth Information
ORing them together, and the resultant pixel color is written to the screen. The third color is usually set to
be the background color, so the color of the pixel that is written is the result of the following operation:
resultant_Color = foreground_color^background_color^current_color
If you remember the discussion of the exclusive OR operation back in Chapter 2, you realize that the effect
of this is to flip between the drawing color and the background color. The first time you draw a shape, the
result is in the current element color. When you draw the same shape a second time, the result is the back-
ground color so the shape disappears. Drawing a third time makes it reappear.
Based on the way XOR mode works, you can now implement the mousePressed() method for the
MouseHander class like this:
public void mousePressed(MouseEvent e) {
start = e.getPoint(); // Save the cursor position
in start
buttonState = e.getButton(); // Record which button was
pressed
if(buttonState == MouseEvent.BUTTON1) {
g2D = (Graphics2D)getGraphics();
// Get graphics context
g2D.setXORMode(getBackground());
// Set XOR mode
}
}
The getGraphics() method that you call in this method is for the view object; the MouseHandler class
has no such method. The method is inherited in the SketcherView class from the Component class. If button
1 was pressed, you obtain a graphics context for the view and store it in g2D , so you must add g2D as a field
in the MouseHandler class:
private Graphics2D g2D = null;
// Temporary graphics context
You pass the color returned by the getBackground() method for the view object to the setXORMode()
method for g2D . This causes objects that you redraw in a given color to switch between the origin color and
the background color. You are able to use this mode in the mouseDragged() method to erase a previously
drawn shape.
With the code in place to handle a button pressed event, you can have a go at implementing
mouseDragged() .
Handling Mouse Dragged Events
You obtain the cursor position in the mouseDragged() method by calling getPoint() for the event object
that is passed as the argument, so you could write:
last = e.getPoint(); // Get cursor position
But you want to handle drag events only for button 1, so you make this conditional upon the but-
tonState field having the value MouseEvent.BUTTON1 .
When mouseDragged() is called for the first time, you won't have created an element. In this case you
can just create one from the points stored in start and last and then draw it using the graphics context
saved by the mousePressed() method. The mouseDragged() method is called lots of times while you drag
Search WWH ::




Custom Search