Reputation: 9
I have some component on the frame and I need it to respond just on right button click. I have to use my own event. Should I extend MouseEvent
? How can I separate right button click from others in my event?
Upvotes: 0
Views: 273
Reputation: 18543
The MouseEvent
class has a method that allows you to check which mouse button was used. It's called getButton and it returns an int
value that you can compare to one of predefined values
On top of that, there's a convenient class called SwingUtilities
, which provides a nice layer of abstraction over the use of these fields. Here's a method you'll find particularly interesting: isRightMouseButton
In other words, you don't need to create your own MouseEvent
, a MouseListener
implementation will suffice. Here's an example of inline implementation, irrelevant details excluded.
new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)){
//do what you want on right click
}
}
// other methods required by the interface
};
Upvotes: 5
Reputation: 285415
No, you wouldn't extend MouseEvent, rather you would use MouseEvent.
If this is a Swing GUI you could add a MouseListener to the component and then in the MouseListener's mousePressed method, get the MouseEvent object that is passed in to the method, get its modifiersEx and then check if right click has been pressed:
public void mousePressed(MouseEvent mEvt) {
if ((mEvt.getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) != 0) {
// right button has been pressed
}
}
Upvotes: 6