Search code examples
javamouselisteneronmouseclickmousemotionlistener

How to set mouseClicked event?


I'm trying to write a program that shows me the x- and y-coordinates when I click my left mouse button, but it doesn't work. The console shows me the x- and y-coordinates automatically if I run the program, but I want to see the coordination after a mouse click.

import java.awt.*;
import java.awt.event.*;
import javax.swing.SwingUtilities;

public class Simple {
    public static void main(String[] args){
        Mouse maus = new Mouse();
        maus.mouseClicked(null);
    }
}

Second file

import java.awt.*;
import java.awt.event.*;

public class Mouse implements MouseListener {
     public void mouseClicked(MouseEvent e) { 
         double mouseX = MouseInfo.getPointerInfo().getLocation().getX();
         double mouseY = MouseInfo.getPointerInfo().getLocation().getY();
         System.out.println(mouseX+"   "+mouseY);
    }
    @Override
    public void mouseEntered(MouseEvent arg0) {}

    @Override
    public void mouseExited(MouseEvent arg0) {}

    @Override
    public void mousePressed(MouseEvent arg0) {}

    @Override
    public void mouseReleased(MouseEvent arg0) {}   
}

Solution

  • What you are doing in your code is writing a MouseListener, but instead of adding it to the GUI components (so it will be activated when the mouse is clicked), you call it yourself. this is why it is executed when you start your program.

    What you need to do is use addMouseListener method on one of your GUI components, and to register your listener to it.

    There's a fairly good guide about it here, also with examples.