用JAVA画一个动态爱心
时间: 2023-11-11 17:05:20 浏览: 86
一篇文章教你用python画动态爱心表白
5星 · 资源好评率100%
好的,以下是用Java代码实现动态爱心的示例:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DynamicHeart extends JPanel implements Runnable {
private int x = 250;
private int y = 350;
private int size = 150;
private int speed = 2;
public void run() {
while (true) {
if (x + size > getWidth() || x < 0) {
speed *= -1;
}
x += speed;
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(x, y - size / 2, size / 2, size / 2);
g.fillOval(x + size / 2, y - size / 2, size / 2, size / 2);
int[] xPoints = { x, x + size / 2, x };
int[] yPoints = { y - size / 4, y + size / 2, y };
g.fillPolygon(xPoints, yPoints, 3);
}
public static void main(String[] args) {
DynamicHeart heart = new DynamicHeart();
JFrame frame = new JFrame("Dynamic Heart");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.add(heart);
frame.setVisible(true);
new Thread(heart).start();
}
}
当你运行这个程序时,会看到一个画有动态心形的窗口。
阅读全文