Ian Twy Ian Twy - 1 month ago 14
Java Question

Java get mouse position on click on Gui

I would like to get the mouse position on click on the swing window itself, NOT on the console on eclipse. Can anyone know how to do that? I'm sorry if it's an obvious question, i'm a beginner. Thx in advance.

Here is the code i got. I somehow found a piece here, but it doesn't really help me like i want.

package shapes;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class mouse {

public static void main(String[] args){

JFrame frame = new JFrame();
JPanel panel = new JPanel();

frame.add(panel);
panel.addMouseListener(new MouseAdapter() {


public void mouseClicked(MouseEvent e) {
int x=e.getX();
int y=e.getY();
System.out.println(x+","+y);
}

}); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200); frame.setVisible(true);




}

}

Answer

You can print the location to a JLabel:

JLabel label = new JLabel();
panel.add(label);
panel.setLayout(null);
frame.add(panel);
panel.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        label.setText("X: "+x+" \t Y: "+y); // this sets the JLabel's text
        label.setBounds(x, y, label.getText().length()*2, 20);
    }
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);

results in this:

this is the result

Comments