用java绘制一个动态爱心
时间: 2024-06-01 14:03:19 浏览: 81
java代码实现动态爱心代码示例
好的,以下是用Java绘制一个动态爱心的代码示例:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class DynamicHeart extends JPanel implements ActionListener {
private int xPoints[] = { 320, 300, 360, 320 };
private int yPoints[] = { 100, 120, 120, 100 };
private int xControl1[] = { 310, 295, 345, 330 };
private int yControl1[] = { 85, 70, 70, 85 };
private int xControl2[] = { 290, 275, 325, 310 };
private int yControl2[] = { 125, 110, 110, 125 };
private int counter = 0;
private Timer timer = new Timer(10, this);
public DynamicHeart() {
timer.start();
}
private void doDrawing(Graphics g) {
g.setColor(Color.RED);
g.fillOval(xPoints[0], yPoints[0], 40, 40);
g.fillOval(xPoints[2], yPoints[2], 40, 40);
g.fillArc(xPoints[1], yPoints[1], 40, 40, 0, -180);
g.setColor(Color.WHITE);
g.fillOval(xPoints[counter % 4], yPoints[counter % 4], 40, 40);
g.fillOval(xPoints[(counter + 2) % 4], yPoints[(counter + 2) % 4], 40, 40);
g.fillPolygon(xPoints, yPoints, 4);
g.setColor(Color.RED);
g.drawCurve(xPoints, yPoints, 4);
g.drawCurve(xPoints, yPoints, 4);
g.setColor(Color.PINK);
g.fillOval(xControl1[counter % 4], yControl1[counter % 4], 10, 10);
g.fillOval(xControl2[counter % 4], yControl2[counter % 4], 10, 10);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
@Override
public void actionPerformed(ActionEvent e) {
counter++;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new DynamicHeart());
frame.setTitle("Dynamic Heart");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
运行后,你将会看到一个动态变化的爱心。
阅读全文