As pointed out in other answers, the place for your work is not in the methods of listening for mouse events.
There is also no explicit “mouse” concept in MouseEvent , so you have to track this yourself. I gave an example of how to do this. Also pay attention to the MouseEvent.BUTTON1 links, as it is easy to track the state of the left mouse button.
Here you should start to learn about concurrency. For this reason, I added a synchronized method, since you need to know that funny things happen when access properties for multiple threads are applied at the same time, and synchronized is a mechanism to maintain this normal functioning. Consider it further outside of this example.
Unconfirmed, but this should work:
volatile private boolean mouseDown = false; public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { mouseDown = true; initThread(); } } public void mouseReleased(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { mouseDown = false; } } volatile private boolean isRunning = false; private synchronized boolean checkAndMark() { if (isRunning) return false; isRunning = true; return true; } private void initThread() { if (checkAndMark()) { new Thread() { public void run() { do {
source share