Reputation: 1042
I am creating a map editor, and where they click will be used to add a data point to the map.
public MapEditor() throws HeadlessException, FileNotFoundException, XMLStreamException {
super("MapEditor");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set JFrame properties.
this.setTitle("Map Editor");
this.setSize(PREFERRED_WIDTH, PREFERRED_HEIGHT);
this.setBackground(Color.gray);
this.setJMenuBar(makeMenuBar());
JPanel mainPanel = new JPanel( new BorderLayout());
Icon image = new ImageIcon("map.jpg");
JLabel label = new JLabel(image);
scrollPane = new JScrollPane();
scrollPane.getViewport().add(label);
scrollPane.addMouseListener(this);
mainPanel.add(scrollPane, BorderLayout.CENTER);
this.getContentPane().add(mainPanel);
this.getContentPane().add(makeStatusBar(), BorderLayout.SOUTH);
setVisible(true);
}
I also have the following event for when the mouse is clicked:
public void mouseClicked(MouseEvent e) {
int x = getX();
int y = getY();
System.out.println("clicked at (" + x + ", " + y + ")");
}
However, no matter where I click in the window, it returns the same value. I have noticed that if I move the entire window to somewhere else on my screen that it returns different values. They appear to correspond to the top left corner of the window. I've tried adding the MouseListener to different components, but I get the same result with each of them. Some help would be greatly appreciated.
Upvotes: 1
Views: 1458
Reputation: 1042
figured it out. It needs to be:
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("clicked at (" + x + ", " + y + ")");
}
before I was just getting the X and Y of the pane, not where the Mouse Event occurred
Upvotes: 0
Reputation: 3321
Use MouseAdapter
instead as it is an abstract adapter class for receiving mouse events.
See the accepted answer of Java MouseListener for code example.
EDIT: You are not using the MouseEvent
variable reference so getX()
and getY()
will not return what you expect, unless getX()
and getY()
are your own methods?
Change your code to:
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("clicked at (" + x + ", " + y + ")");
}
Upvotes: 5