KidLet
KidLet

Reputation: 183

How can I capture all mouse events in Java?

I want to capture mouse events in Swing Component, like MouseDrag Event etc, but I have found there are some events missing when I move my mouse very quickly,

It seems not all of the events are captured. The trace of mouse I captured is discrete but I want to the trace of mouse and the precision is 1 pixel.

Could you help me please? Thanks a lot.

Upvotes: 1

Views: 907

Answers (3)

JayC667
JayC667

Reputation: 2576

One really easy solution - especially when it comes to painting - is using the provided Graphics and Graphics2D objects:

static class MyPanel extends JPanel {
    private static final long serialVersionUID = -5482850214654836564L;

    private int lastX = -1;
    private int lastY = -1;
    public MyPanel() {
        super(true); // activate double buffering
        addMouseListener(new MouseAdapter() {
            @Override public void mousePressed(final MouseEvent pE) {
                final int newX = pE.getX();
                final int newY = pE.getY();
                final Graphics g = getGraphics();
                if (g == null) return; // panel not visible
                g.drawLine(lastX, lastY, newX, newY); // or add to list
                lastX = newX;
                lastY = newY;
            }
        });
    }
}

public static void main(final String[] args) {
    final JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.setBounds(200, 200, 400, 400);

    f.add(new MyPanel());

    f.setVisible(true);
}

For a more consistent system take a look into Java Shapes (RoundRectangle, Polygon) etc. Those could be created in the listener part, then stored in a list, and inside the paint()/paintComponent() method you could draw those shapes with g.fill() or g.drawPolygon(p).

Upvotes: 0

JayC667
JayC667

Reputation: 2576

If you only want to capture mouse movement on a certain Component, then the MouseDrag event etc will be all you need. As Matti Virkkunen said, you have to do point-to-point interpolation if you want to have a continuous line.

If you are asking about capturing all events that happen inside a Container and its sub-components, then you might consider accessing the EventQueues. However, I have no actual knowledge of that, but a search on google might get you where u need.

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

You can't do this. Not even the mouse itself reports every single pixel (or whatever unit it uses) to the computer.

You'll have to interpolate the missing points. A single linear interpolation should do the trick.

Upvotes: 5

Related Questions