怪怪怪!Applet的刷新问题

sandliu 2006-11-14 09:55:51
有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);
}
}



...全文
216 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sandliu 2006-11-16
  • 打赏
  • 举报
回复
谢谢,第二个问题解决了,在start和stop中加了repaint。
但第一个依旧。。。。
sandliu 2006-11-16
  • 打赏
  • 举报
回复
repaint就是清除以前的图像,然后自动调用paint的
malligator 2006-11-16
  • 打赏
  • 举报
回复
mark
  • 打赏
  • 举报
回复
只顾着在新位置画图,而没有清除上次位置的图像
jayfantsy 2006-11-15
  • 打赏
  • 举报
回复
有点难,线程还要仔细看看..

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧