我通过一些代码java applet和动画,我写了下面的代码:
import java.applet.*;
import java.awt.*;
/*<applet code="AppletDemo" width = 200 height = 100></applet>
*/
public class AppletDemo extends Applet implements Runnable
{
String msg = "Text Animating from right to left...";
Thread t = null;
int state;
boolean stopFlag;
int msgX = 200;
String s;
boolean diff;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.black);
}
public void start()
{
t = new Thread(this);
stopFlag = false;
t.start();
s = "abc";
diff = s.equalsIgnoreCase("abc");
}
public void run()
{
while (true)
{
try{
if(msgX>=-150)
msgX--;
else
msgX =200;
Thread.sleep(10);
repaint();
}
catch(Exception e)
{}
}
}
public void paint(Graphics g)
{
g.drawString(msg,msgX,20);
showStatus(diff+"Text at "+msgX+",20");
}
}
发生了什么事情,当我把Thread.sleep(100),它工作正常,但当我尝试动画更快的Thread.sleep(10)它开始闪烁,我无法理解发生了什么可以任何人的帮助.
解决方法:
>不要直接在顶层容器上涂漆.使用JPanel在其上绘画.
>不要使用Thread.sleep().最好使用Swing Timer进行动画制作.
>覆盖JPanel的paintComponent()方法以进行自定义绘制.
>不要忘记在重写的paintComponent方法中调用super.paintComponent().
而不是无限循环尝试与Swing Timer.
示例代码:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.Timer;
/*
* <applet code="AppletDemo" width = 200 height = 100></applet>
*/
public class AppletDemo extends Applet {
String msg = "Text Animating from right to left...";
int state;
boolean stopFlag;
int msgX = 200;
String s;
boolean diff;
JPanel panel;
public void init() {
setBackground(Color.cyan);
setForeground(Color.black);
panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawString(msg, msgX, 20);
showStatus(diff + "Text at " + msgX + ",20");
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 40);
}
};
add(panel);
int delay = 10; // milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (msgX >= -150)
msgX--;
else
msgX = 200;
repaint();
}
};
Timer timer = new Timer(delay, taskPerformer);
timer.setRepeats(true);
timer.start();
}
}