Java Reference
In-Depth Information
public void mousePressed(MouseEvent mouseEvent) {
int modifiers = mouseEvent.getModifiers();
if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) {
System.out.println("Middle button pressed.");
}
}
Although this works fine and dandy, the SwingUtilities class has three methods to make
this process much simpler:
SwingUtilities.isLeftMouseButton(MouseEvent mouseEvent)
SwingUtilities.isMiddleMouseButton(MouseEvent mouseEvent)
SwingUtilities.isRightMouseButton(MouseEvent mouseEvent)
Now, instead of needing to manually get the modifiers and compare them against the
mask, you can simply ask the SwingUtilities , as follows:
if (SwingUtilities.isMiddleMouseButton(mouseEvent)) {
System.out.println("Middle button released.");
}
This makes your code much more readable and easier to maintain.
Listing 2-2 contains an updated ButtonSample that adds another listener to detect which
mouse button was pressed.
Listing 2-2. Button Sample with Mouse Button Detection
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Button Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Select Me");
// Define ActionListener
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("I was selected.");
}
};
Search WWH ::




Custom Search