Java小程序线程动画 [英] Java Applet Thread Animation
本文介绍了Java小程序线程动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过一些code Java Applet和动画的走了,我写了下面的code:
I am gone through some of code java applet and animation, i write the following code :
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");
}
}
正在发生的事情是,当我把视频下载(100),它工作正常,但是当我尝试更快的动画是视频下载(10),它开始闪烁,我不明白发生了什么事谁能帮助。
What is happening is that when i put Thread.sleep(100), it works fine but when i try to animate faster that is Thread.sleep(10) it starts flickering , i couldn't understand what is happening can anyone help.
推荐答案
- 请不要在顶层容器直接作画。使用
的JPanel
画就可以了。 - 请不要使用
视频下载()
。这是更好地使用秋千
定时器动画。 - 覆盖
的paintComponent()
定制油画的JPanel
的方法。 - 请不要忘记调用
super.paintComponent方法()
内覆盖的paintComponent
方法。
- Don't directly paint over top level container. Use
JPanel
to paint on it. - Don't use
Thread.sleep()
. It's better to useSwing
Timer for animation. - Override
paintComponent()
method ofJPanel
for custom painting. - Don't forget to call
super.paintComponent()
inside overriddenpaintComponent
method.
而不是无限循环使用摇摆定时器一>
请看看如何使用Swing计时器
样code:
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();
}
}
查找样品code这里
这篇关于Java小程序线程动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文