【发布时间】:2011-11-18 04:20:06
【问题描述】:
我正在创建一个地图编辑器,他们单击的位置将用于向地图添加数据点。
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);
}
当鼠标被点击时,我也有以下事件:
public void mouseClicked(MouseEvent e) {
int x = getX();
int y = getY();
System.out.println("clicked at (" + x + ", " + y + ")");
}
但是,无论我在窗口中的哪个位置单击,它都会返回相同的值。我注意到,如果我将整个窗口移动到屏幕上的其他位置,它会返回不同的值。它们似乎对应于窗口的左上角。我尝试将 MouseListener 添加到不同的组件中,但每个组件都得到相同的结果。一些帮助将不胜感激。
【问题讨论】:
-
getX 和 getY 方法里面有什么?
标签: java swing mouseevent mouselistener