user1795687
user1795687

Reputation: 11

How to listen to mouse move-events while mouse button is pressed in Java

I have a problem with mouse events in my program. I'm trying to code a drawing program with a canvas.

The user should draw if he left-clicks and moves the mouse. So I defined a class Drawer with a boolean allow_draw in it, and I added a method draw.

draw is called with a mousemoved event in the canvas and allow_draw is set true and false with mousepressed and released.

However, mousemoved isn't firing while I press the mouse button...

My question is: how can I listen to mouse movements while a mouse button is pressed.

Hope you know what I'm looking for :)

Upvotes: 1

Views: 3295

Answers (3)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285440

You should consider,

  • using a combination of MouseListener and MouseMotionListener, which is conveniently combined in the MouseAdapter class.
  • Turn drawing on when mousePressed occurs.
  • Turn drawing off when mouseReleased occurs
  • Draw within mouseDragged if drawing is on (use an if block).
  • Add your MouseAdapter object twice to the component, with the addMouseListener(...) method and the addMouseMotionListener(...) method.

Upvotes: 1

sarcan
sarcan

Reputation: 3165

A mouse move event with a pressed button would be a drag event. Simply listen to 'MouseListener#mouseDragged', it is what you're looking for.

Upvotes: 0

RWVan3
RWVan3

Reputation: 31

Can you please post your source code? Please try adding a MouseMotionListener. Here is an example from a project I am working on.

addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {

        public void mouseDragged(java.awt.event.MouseEvent evt) {
            formMouseDragged(evt);
        }
        public void mouseMoved(java.awt.event.MouseEvent evt) {
            formMouseMoved(evt);
        }
    });`

Upvotes: 2

Related Questions