Java mouse pressed - without events
java
Solution
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.
Problem
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