写动画程序,界面如下图所示。要求绘制一只兔子,令其从界面左端出发,移动到界面右端后停止
时间: 2024-03-17 18:42:22 浏览: 87
以下是一个简单的Java动画程序,绘制一只兔子,让它从左端移动到右端并停止。这个程序使用Java Swing库来创建GUI,使用Java Graphics2D库来绘制兔子。
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RabbitAnimation extends JPanel implements Runnable {
private static final int WIDTH = 600;
private static final int HEIGHT = 400;
private static final int RABBIT_WIDTH = 100;
private static final int RABBIT_HEIGHT = 80;
private static final int DELAY = 10;
private int rabbitX;
private Thread animator;
public RabbitAnimation() {
rabbitX = -RABBIT_WIDTH;
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.ORANGE);
g2d.fillOval(rabbitX, HEIGHT / 2 - RABBIT_HEIGHT / 2, RABBIT_WIDTH, RABBIT_HEIGHT);
}
public void run() {
while (rabbitX < WIDTH) {
rabbitX += 1;
repaint();
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
}
}
public void start() {
animator = new Thread(this);
animator.start();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Rabbit Animation");
RabbitAnimation rabbit = new RabbitAnimation();
frame.add(rabbit);
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rabbit.start();
}
}
```
这个程序通过继承JPanel类来创建一个自定义面板,然后在面板上绘制兔子。它使用一个线程来控制兔子的位置,并在每次移动后重新绘制兔子。程序在启动时创建一个JFrame窗口,将自定义面板添加到窗口中,并启动线程来控制动画。
阅读全文