Java编写程序,使得当按下鼠标时显示鼠标的位置。
时间: 2024-03-01 10:49:55 浏览: 71
基于JavaScript实现 获取鼠标点击位置坐标的方法
5星 · 资源好评率100%
可以使用Java Swing编写一个简单的程序实现该功能,具体代码如下:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MousePositionDemo extends JFrame implements MouseListener, MouseMotionListener {
JLabel label;
public MousePositionDemo() {
super("Mouse Position Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setLayout(new BorderLayout());
label = new JLabel("Move the mouse over the window");
add(label, BorderLayout.SOUTH);
addMouseListener(this);
addMouseMotionListener(this);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
// do nothing
}
public void mouseEntered(MouseEvent e) {
// do nothing
}
public void mouseExited(MouseEvent e) {
// do nothing
}
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
label.setText("Mouse pressed at (" + p.x + ", " + p.y + ")");
}
public void mouseReleased(MouseEvent e) {
Point p = e.getPoint();
label.setText("Mouse released at (" + p.x + ", " + p.y + ")");
}
public void mouseDragged(MouseEvent e) {
// do nothing
}
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
label.setText("Mouse moved to (" + p.x + ", " + p.y + ")");
}
public static void main(String[] args) {
new MousePositionDemo();
}
}
```
在该程序中,我们实现了MouseListener和MouseMotionListener接口,同时添加了鼠标事件和鼠标移动事件的监听器。当鼠标按下或释放时,会在标签上显示鼠标的位置,当鼠标移动时,标签也会实时更新鼠标的位置。
阅读全文