Java Reference
In-Depth Information
First, you need to find out which button is pressed. It is generally a good idea to make mouse button oper-
ations specific to a particular button. That way you avoid potential confusion when you extend the code to
support more functionality. The getButton() method for the MouseEvent object that is passed to a handler
method returns a value of type int that indicates which of the three mouse buttons changed state. The value
is one of four constants that are defined in the MouseEvent class:
BUTTON1 BUTTON2 BUTTON3 NOBUTTON
On a two-button mouse or a wheel mouse, BUTTON1 for a right-handed user corresponds to the left button
and BUTTON2 corresponds to the right button. BUTTON3 corresponds to the middle button when there is one.
NOBUTTON is the return value when no button has changed state.
You can record the button state in the handler object. First add a member to the MouseHandler class to
store the button state:
private int buttonState = MouseEvent.NOBUTTON;
// Records button state
You can record which button is pressed by using the following code in the mousePressed() method:
public void mousePressed(MouseEvent e) {
buttonState = e.getButton();
// Record which button was pressed
if(buttonState == MouseEvent.BUTTON1) {
// Code to handle button 1 press...
}
}
By recording the button state, you make it available to the mouseDragged() method. The button state
won't change during a mouse dragged event so if you don't record it when the mouse pressed event occurs,
the information about which button is pressed is lost.
The MouseEvent object that is passed to all mouse handler methods records the current cursor position,
and you can get a Point reference to it by calling the getPoint() method for the object. For example:
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) {
// Code to handle button 1 press...
}
}
The mouseDragged() method is going to be called very frequently, and to implement rubber-banding of
the element, the element must be redrawn each time so it needs to be very fast. You don't want to have the
whole view redrawn each time, as this carries a lot of overhead. You need an approach that redraws just the
element.
Using XOR Mode
One way to implement rubber-banding 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
Search WWH ::




Custom Search