在JFrame里生成一个panel并添加MouseMotionListner监听,实时在控制台显示鼠标拖拽时坐标位置及时间。
时间: 2024-03-03 19:48:00 浏览: 68
实时记录鼠标位置坐标
4星 · 用户满意度95%
好的,可以通过以下代码实现:
```
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MouseMotionListenerDemo extends JFrame {
private static final long serialVersionUID = 1L;
public MouseMotionListenerDemo() {
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(400, 400));
panel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("X坐标: " + e.getX() + ", Y坐标: " + e.getY() + ", 时间: " + sdf.format(new Date()));
}
});
this.add(panel);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
new MouseMotionListenerDemo();
}
}
```
这段代码会创建一个 JFrame,里面放置了一个 JPanel,并为该 JPanel 添加了 MouseMotionListener 监听器,当鼠标拖拽时,会实时在控制台显示鼠标的坐标位置及时间。
阅读全文