java实现一个动态爱心
时间: 2023-12-04 08:33:13 浏览: 78
java代码实现动态爱心代码示例
很高兴回答您的问题!以下是使用Java实现一个动态爱心的代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DynamicHeart extends JFrame implements ActionListener {
private Timer timer;
private int x;
private int y;
private int size;
private final int DELAY = 50;
public DynamicHeart() {
setTitle("Dynamic Heart");
setSize(500, 500);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 200;
y = 200;
size = 50;
timer = new Timer(DELAY, this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
Polygon left = new Polygon();
left.addPoint(x, y);
left.addPoint(x + size, y + size);
left.addPoint(x, y + size * 2);
left.addPoint(x - size, y + size);
Polygon right = new Polygon();
right.addPoint(x, y);
right.addPoint(x - size, y + size);
right.addPoint(x, y + size * 2);
right.addPoint(x + size, y + size);
g2d.fill(left);
g2d.fill(right);
}
public void actionPerformed(ActionEvent e) {
x = x + (int) (Math.random() * 21 - 10);
y = y + (int) (Math.random() * 21 - 10);
size = size + (int) (Math.random() * 6 - 3);
if (size < 2) {
size = 2;
}
if (x > getWidth()) {
x = 0;
}
if (x < 0) {
x = getWidth();
}
if (y > getHeight()) {
y = 0;
}
if (y < 0) {
y = getHeight();
}
repaint();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
DynamicHeart dh = new DynamicHeart();
dh.setVisible(true);
});
}
}
```
在这个例子中,我们使用Java的Swing和AWT库创建了一个窗口,并实现了一个动态的爱心形状。使用定时器来定期更新爱心的位置和大小,并使用随机数添加一些变化。当爱心变得太小时,我们将它限制为最小的大小。如果爱心移动到窗口边缘之外,它将重新出现在窗口的另一侧。最后,我们调用repaint()方法重绘窗口,使我们的动态爱心形状能够更新。
阅读全文