is there a way, in Java, to directly check whether one of the mouse buttons is down without using events, listeners etc. ? I'd like to have a thread that, every 100 milliseconds or so, checks whether a mouse button is down and then does something. So if the user holds a mouse button down for a while it will trigger several responses.
So what I'm looking for is a method that gives the state of the mouse, without going through the usual event - handling system.
thanks
4 Answers 4
I believe this is not possible in Java. Well it's possible through JNI but that is a world of pain.
Doing this with events is not hard, and will integrate much better with the rest of your app. Here's an example of writing to the console every 100 ms while the mouse button is pressed:
import javax.swing.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
final JLabel label = new JLabel("Click on me and hold the mouse button down");
label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.getContentPane().add(label);
label.addMouseListener(new TimingMouseAdapter());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class TimingMouseAdapter extends MouseAdapter {
private Timer timer;
public void mousePressed(MouseEvent e) {
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Mouse still pressed...");
}
});
timer.start();
}
public void mouseReleased(MouseEvent e) {
if (timer != null) {
timer.stop();
}
}
}
}
Modifying this to do different things (such as changing paintbrush mode) after different periods time should be straight-forward.
Comments
I don't know whether this is possible - maybe it is.
However, you can always write an event handler whose sole job is to keep track of the current mouse state. Then your 100ms code could just query it.
Whether or not it's possible, are you sure you want to do this?
It seems to me that you're likely to miss clicks that way. 100 milliseconds is a tenth of a second.. Many clicks don't last that long.
And even if you make your polling loop shorter, all you're doing is to narrow the window during which you could miss a click, so it'll miss clicks less often. But it'll still be a race condition.
I'm guessing that your concern about complication stems from having to deal with threading issues, but unless you give us more information, we can't give you much help.
2 Comments
It should be easy enough to write a Listener to handle the mouse state. See Global Event Listeners for an introduction to the AWTEventListener which allows you you listener to all mouse events with a single listener.
Then in the listener you would start your Timer.