作为Applet程序的一个入门,我们今天探讨一下如何实现一个半径不断增大的小球动画,正如下图所示。
设计的关键思想:
我们需要设定一个小球的圆心坐标,最好是在窗口的中央,然后令小球的半径不断增大,不断的重绘,以实现小球的增大动画。
设计方案:
我们要绘制小球,就用到了一个Graphics类,Graphics类有绘制的功能。
然后再设计一个线程专门用来控制动画的播放,我们重载run()方法,在其中实现小球半径的增加,以及调用窗体的重绘函数,每隔一定时间重绘窗体。
接下来实现paint(Graphics g)函数,来绘制一个彩色圆球,这个函数中要做的就很简单了,用特定的颜色覆盖一个一定大小的圆形区域
下面就是源代码
import java.awt.*;
import java.applet.Applet;
import javax.swing.JApplet;
public class Circle extends JApplet implements Runnable{
int x;//圆心x坐标 为x-r/2
int y;//圆心y坐标 为y-r/2
int r;//半径
private Image img;
private Graphics graph;
public void init(){
Dimension de = this.getSize();
x = de.height/2;
y = de.width/2;
r = 1;
};
public void start(){
//定义一个线程
Dimension de = this.getSize();
x = de.height/2;
y = de.width/2;
r = 1;
Thread animation = new Thread(this);
animation.start();
}
public void stop(){
}
public void destroy(){
}
public void run(){
Dimension de1 = this.getSize();
while(true){
r += 1;
if(r>(de1.height/2)||r>(de1.width/2)){
r = 1;;
}
repaint();
try
{
// 暂停线程30毫秒
Thread.sleep (30);
}
catch (InterruptedException ex)
{
}
}
}
public void paint (Graphics g) {
//设置球的颜色
g.setColor (Color.PINK);
// 从x-r/2,y-r/2位置处画一个实心的圆
g.fillOval(x-r/2,y-r/2,r,r);
}
//双缓冲机制
public void update (Graphics g)
{
// 初始化buffer
if (img == null)
{
img = createImage (this.getSize().width, this.getSize().height);
graph = img.getGraphics ();
}
// 后台清屏,即设置圆球组件和后台一样的颜色,大小
graph.setColor (getBackground ());
graph.fillRect (0, 0, this.getSize().width, this.getSize().height);
// 绘制相应的元素组件
graph.setColor (getForeground());
paint (graph);
// 在屏幕上重画已经绘制好的圆
g.drawImage (img, 0, 0, this);
}
}
这个程序的update(Graphics g)函数是我借鉴了别人的代码,为了重绘时的平滑不闪屏,个人理解不是很深。
在run()方法中,我试图用r来控制小球的大小,当半径到达屏幕的最大范围时,回到原始尺寸,重新开始,只是运行结果不如所设想的,
在此也恳请大家为我指点迷津呢