我经历了一些代码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)它开始闪烁,我无法理解发生了什么任何人都可以帮忙。
答案 0 :(得分:1)
JPanel
在上面绘画。Thread.sleep()
。最好使用Swing
计时器进行动画制作。paintComponent()
JPanel
方法进行自定义绘制。super.paintComponent()
方法中调用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();
}
}
答案 1 :(得分:0)
是的,它会闪烁。您必须使用DoubleBuffering的概念来解决此问题。这意味着要绘制的图像在屏幕上绘制之前已经被缓冲。它将消除闪烁效应。