java动态爱心代码
时间: 2023-11-14 08:12:58 浏览: 104
java代码实现动态爱心代码示例
Java动态爱心代码可以通过使用Java Swing库来实现。以下是一个简单的示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class DynamicHeart extends JPanel implements Runnable {
private Thread animator;
private double angle = 0;
private double scale = 1;
public DynamicHeart() {
setBackground(Color.white);
setPreferredSize(new Dimension(400, 400));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.translate(getWidth() / 2, getHeight() / 2);
g2d.rotate(angle);
g2d.scale(scale, scale);
Path2D path = new Path2D.Double();
path.moveTo(0, 0);
path.curveTo(0, -50, -80, -50, -80, -20);
path.curveTo(-80, -50, -160, -50, -160, -20);
path.curveTo(-160, -50, -240, -50, -240, 0);
path.curveTo(-240, 30, -160, 30, -160, 10);
path.curveTo(-160, 30, -80, 30, -80, 10);
path.curveTo(-80, 30, 0, 30, 0, 0);
g2d.setColor(Color.red);
g2d.fill(path);
}
public void addNotify() {
super.addNotify();
animator = new Thread(this);
animator.start();
}
public void run() {
while (true) {
angle += Math.PI / 100;
scale = Math.abs(Math.sin(angle));
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Dynamic Heart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DynamicHeart());
frame.pack();
frame.setVisible(true);
}
}
```
这个代码使用了Java的Swing库来创建一个JPanel,并在其中绘制了一个心形图案。通过使用线程来控制心形图案的旋转和缩放,实现了动态效果。你可以将这个代码复制到你的Java开发环境中运行,看看效果如何。
阅读全文