怪怪怪!Applet的刷新问题
有2个程序都遇到麻烦了,但一直不知道问题出在那儿
1、一个小球,在屏幕上来回走。但刷新有问题,只有当窗口缩放时才清除以前的图像
import java.awt.*;
import javax.swing.*;
public class BouncingCircle extends JApplet implements Runnable {
int x = 150, y = 50, r = 50; // 圆的位置和半径
int dx = 11, dy = 7; // 圆的轨迹
Thread animator; // 产生动态效果的线程
volatile boolean pleaseStop; // 线程结束的标记
//在当前的位置画圆
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillOval(x - r, y - r, r * 2, r * 2);
}
/**
* 重新设定圆的位置,并执行重画操作
* 不断被线程调用
**/
public void animate() {
// 到达边界时反弹
Rectangle bounds = getBounds();
if ((x - r + dx < 0) || (x + r + dx > bounds.width))
dx = -dx;
if ((y - r + dy < 0) || (y + r + dy > bounds.height))
dy = -dy;
// 重新设定圆的位置
x += dx;
y += dy;
repaint();
}
// 实现Runnable接口的run方法
public void run() {
while (!pleaseStop) { // Loop until we're asked to stop
animate(); // 重画操作
try {
Thread.sleep(100);
}
catch (InterruptedException e) {
}
}
}
/** 当applet被加载时启动线程 */
public void start() {
animator = new Thread(this); // 创建线程
pleaseStop = false;
animator.start(); /*线程开始运行*/
}
/** 当applet关闭时线程停止 */
public void stop() {
pleaseStop = true;
}
}
2、Applet中,init方法与stop方法会被多次执行,写了一个程序测试,好像没有多次执行。
import java.applet.*;
import java.awt.*;
public class LifeCycle extends Applet
{
private int InitCnt;
private int StartCnt;
private int StopCnt;
private int DestroyCnt;
private int PaintCnt;
public LifeCycle()
{
InitCnt=0; StartCnt=0; StopCnt=0; DestroyCnt=0; PaintCnt=0;
}
public void init()
{
InitCnt++;
}
public void start()
{
StartCnt++;
}
public void detroy()
{
DestroyCnt++;
}
public void stop()
{
StopCnt++;
}
public void paint(Graphics g)
{
PaintCnt++;
g.drawLine(20,200,300,200); g.drawLine(20,200,20,20);
g.drawLine(20,170,15,170); g.drawLine(20,140,15,140);
g.drawLine(20,110,15,110);
g.drawLine(20,80,15,80);
g.drawLine(20,50,15,50);
g.drawString("Init()",25,213);
g.drawString("Start()",75,213);
g.drawString("Stop()",125,213);
g.drawString("Destroy()",175,213);
g.drawString("Paint()",235,213);
g.drawString(""+InitCnt,25,223);
g.drawString(""+StartCnt,75,223);
g.drawString(""+StopCnt,125,223);
g.drawString(""+DestroyCnt,175,223);
g.drawString(""+PaintCnt,235,223);
g.fillRect(25,200-InitCnt*10,40,InitCnt*10);
g.fillRect(75,200-StartCnt*10,40,StartCnt*10);
g.fillRect(125,200-StopCnt*10,40,StopCnt*10);
g.fillRect(175,200-DestroyCnt*10,40,DestroyCnt*10);
g.fillRect(235,200-PaintCnt*10,40,PaintCnt*10);
}
}