java画跳动的爱心代码
时间: 2023-09-21 14:09:46 浏览: 305
李峋同款爱心代码,爱心跳动
下面是一个简单的Java代码示例,用于绘制跳动的爱心:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JumpingHeart extends JFrame implements ActionListener {
private Timer timer;
private int x, y;
private int dx, dy;
public JumpingHeart() {
x = 200;
y = 200;
dx = 2;
dy = 2;
timer = new Timer(10, this);
timer.start();
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillOval(x, y, 100, 100);
g2d.fillOval(x + 100, y, 100, 100);
int[] xPoints = {x, x + 200, x + 100};
int[] yPoints = {y + 100, y + 100, y + 200};
g2d.fillPolygon(xPoints, yPoints, 3);
}
public void actionPerformed(ActionEvent e) {
if (x < 0 || x > 400) {
dx = -dx;
}
if (y < 0 || y > 400) {
dy = -dy;
}
x += dx;
y += dy;
repaint();
}
public static void main(String[] args) {
new JumpingHeart();
}
}
```
这个程序使用Java的Swing库绘制了一个跳动的爱心。通过定时器和动画效果,爱心会在窗口中上下左右跳动。你可以将这段代码复制到一个Java文件中,然后运行它来看到效果。希望这对你有帮助!
阅读全文