Java Reference
In-Depth Information
private boolean button1Down = false; // Flag for button 1 state
Now we can store the state when the mousePressed() method executes:
public void mousePressed(MouseEvent e) {
start = e.getPoint(); // Save the cursor position in start
if(button1Down = (e.getButton() == MouseEvent.BUTTON1)) {
// Rest of the code to handle button 1 press...
}
}
The mouseDragged() method is going to be called very frequently, and to implement rubber-banding
of the element each time, the redrawing of the element needs to be very fast. We don't want to have the
whole view redrawn each time, as this will carry a lot of overhead. We need a different approach.
Using XOR Mode
One way to do this is to draw in XOR mode . You set XOR mode by calling the setXORMode()
method for a graphics context, and passing a color to it - usually the background color. In this mode the
pixels are not written directly to the screen. The color in which you are drawing is combined with the
color of the pixel currently displayed together with a third color that you specify, by exclusive 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
The effect of this is to flip between the drawing color and the background color. The first time you draw
a shape, the result will be in the color you are drawing with, except for overlaps with other shapes, since
they won't be in the background color. When you draw the same shape a second time the result will be
the background color so the shape will disappear. Drawing a third time will make it reappear. We saw
how this works back in Chapter 2 when we were discussing the bitwise exclusive OR operation.
Based on what we have said, we can implement the mousePressed() method for the MouseHander
class like this:
public void mousePressed(MouseEvent e) {
start = e.getPoint(); // Save the cursor position in start
if(button1Down = (e.getButton() == MouseEvent.BUTTON1)) {
g2D = (Graphics2D)getGraphics(); // Get graphics context
g2D.setXORMode(getBackground()); // Set XOR mode
g2D.setPaint(theApp.getWindow().getElementColor()); // Set color
}
}
If button 1 was pressed, we obtain a graphics context for the view, so we must add another member to
the MouseHandler class to store this:
private Graphics2D g2D = null; // Temporary graphics context
Search WWH ::




Custom Search