java实现创建页面插入飞机图片并添加鼠标监听,让飞机跟着鼠标移动
时间: 2024-04-09 18:33:46 浏览: 16
你可以使用Java Swing来实现创建页面并插入飞机图片,然后添加鼠标监听器。下面是一个简单的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PlaneGame extends JFrame {
private ImageIcon planeIcon;
private JLabel planeLabel;
public PlaneGame() {
// 创建窗口
setTitle("Plane Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(null);
// 加载飞机图片
planeIcon = new ImageIcon("plane.png");
planeLabel = new JLabel(planeIcon);
planeLabel.setSize(planeIcon.getIconWidth(), planeIcon.getIconHeight());
planeLabel.setLocation(0, 0);
// 添加鼠标监听器
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
// 飞机跟随鼠标移动
int x = e.getX() - planeLabel.getWidth() / 2;
int y = e.getY() - planeLabel.getHeight() / 2;
planeLabel.setLocation(x, y);
}
});
// 添加飞机图片到窗口
getContentPane().add(planeLabel);
// 显示窗口
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PlaneGame();
}
});
}
}
```
请将上面示例代码中的 "plane.png" 替换为你自己的飞机图片路径。运行代码后,会显示一个窗口,并且飞机图片会跟随鼠标移动。