Ale*_*lex 1 java swing mouseevent mouselistener
我正在创建一个地图编辑器,它们点击的位置将用于向地图添加数据点.
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);
}
Run Code Online (Sandbox Code Playgroud)
单击鼠标时我也有以下事件:
public void mouseClicked(MouseEvent e) {
int x = getX();
int y = getY();
System.out.println("clicked at (" + x + ", " + y + ")");
}
Run Code Online (Sandbox Code Playgroud)
但是,无论我在窗口中单击何处,它都会返回相同的值.我注意到如果我将整个窗口移动到屏幕上的其他位置,它会返回不同的值.它们似乎对应于窗口的左上角.我已经尝试将MouseListener添加到不同的组件,但我得到了相同的结果.一些帮助将不胜感激.
请MouseAdapter改为使用,因为它是用于接收鼠标事件的抽象适配器类.
有关代码示例,请参阅Java MouseListener的已接受答案.
编辑:您没有使用MouseEvent可变的参考,因此getX()并getY()不会返回你所期望的,除非getX()和getY()有自己的方法?
将您的代码更改为:
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("clicked at (" + x + ", " + y + ")");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1314 次 |
| 最近记录: |