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.
Use
MouseAdapterinstead 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
MouseEventvariable reference sogetX()andgetY()will not return what you expect, unlessgetX()andgetY()are your own methods?Change your code to: