调用鼠标事件中的坐标
时间: 2023-09-18 07:08:05 浏览: 42
可以通过MouseEvent对象的getX()和getY()方法获取鼠标事件发生时的坐标。getX()方法返回鼠标事件在组件内的x坐标,getY()方法返回鼠标事件在组件内的y坐标。
例如,在鼠标点击事件中获取鼠标点击的坐标:
```java
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("鼠标点击坐标:(" + x + ", " + y + ")");
}
```
在鼠标移动事件中获取鼠标移动的坐标:
```java
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("鼠标移动坐标:(" + x + ", " + y + ")");
}
```
注意,在使用鼠标事件时,需要添加MouseListener或MouseMotionListener监听器,例如:
```java
JButton button = new JButton("Click me");
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("鼠标点击坐标:(" + x + ", " + y + ")");
}
});
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)