用JAVA写一个会动的爱心代码
时间: 2023-05-26 11:04:34 浏览: 97
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MovingHeart extends JFrame implements ActionListener {
private JButton btnStart;
private MovingPanel movingPanel;
public MovingHeart() {
super("Moving Heart");
//创建控制面板和开始按钮
JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
btnStart = new JButton("Start");
btnStart.addActionListener(this);
controlPanel.add(btnStart);
add(controlPanel, BorderLayout.NORTH);
// 创建移动面板
movingPanel = new MovingPanel();
add(movingPanel, BorderLayout.CENTER);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//按钮点击事件
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
movingPanel.startAnimation(); //开始动画
}
}
public static void main(String[] args) {
MovingHeart frame = new MovingHeart();
frame.setSize(600, 600);
frame.setVisible(true);
}
}
//移动面板
class MovingPanel extends JPanel implements Runnable {
private final int W = 200; // 爱心的宽度
private final int H = 200; // 爱心的高度
private final int INTERVAL = 50; //更新动画的时间间隔
private Image image;
private int x, y; //图片位置
private int dx = 5, dy = 5; //每次移动的距离
private Thread animation;
public MovingPanel() {
ImageIcon icon = new ImageIcon(getClass().getResource("heart.png"));
image = icon.getImage();
setPreferredSize(new Dimension(W, H));
// 设置随机位置
x = (int) (Math.random() * (getWidth() - W));
y = (int) (Math.random() * (getHeight() - H));
}
//开始动画,创建线程并启动
public void startAnimation() {
if (animation == null) {
animation = new Thread(this);
animation.start();
}
}
//线程循环
public void run() {
while (true) {
x += dx;
y += dy;
//检测是否碰到边界
if (x < 0 || x + W > getWidth()) {
dx = -dx;
}
if (y < 0 || y + H > getHeight()) {
dy = -dy;
}
//重绘
repaint();
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
break;
}
}
}
// 绘制爱心
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, x, y, this);
}
}
```
需要一个名为“heart.png”的心形图片,放在同一个文件夹下。
阅读全文