Java 动画在不移动鼠标光标时出现卡顿
我有一个非常简单的动画,一个大字体的文本连续(一个像素一个像素地)向左移动。首先将文本转换为图像,然后启动计时器任务,该任务重复(每10-20毫秒)将图像的x坐标递减1,并进行重绘()。
此程序在某些系统上显示奇怪的行为。在我的PC上使用nVidia卡,它可以平稳运行。在我的Vaio笔记本上,在BeagleBoneBlack上,在朋友的Mac上,它结结巴巴。它似乎暂停了一段时间,然后向左跳了大约10个像素,再次暂停,依此类推。
令我感到困惑的是,在这些系统上,只有当您不触摸鼠标时,动画才会卡顿下来。只要您在窗口内移动鼠标光标,无论多么缓慢,或者拖动窗口本身,动画运行得非常流畅!
谁能解释一下吗?这是程序:
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
class Textimg extends JComponent
{
String str;
Font font;
int x = 0;
final int ytext = 136;
Image img;
public Textimg(String s)
{
str = s;
font = new Font("Noserif", Font.PLAIN, 96);
setLayout(null);
}
protected void paintComponent(Graphics g)
{
if (img == null)
{
img = createImage(4800, 272);
Graphics gr = img.getGraphics();
gr.setFont(font);
gr.setColor(Color.BLACK);
gr.fillRect(0, 0, 4800, 272);
gr.setColor(new Color(135, 175, 0));
gr.drawString(str, 0, ytext);
gr.dispose();
}
g.drawImage(img, x, 0, this);
}
public void addX(int dif)
{
if (isVisible())
{
x = x + dif;
Graphics g = getGraphics();
if (g != null) paintComponent(g);
}
}
}
public class Banner extends JFrame
{
StringBuffer buf;
int sleeptime = 10;
Banner(String path) throws IOException
{
setSize(new Dimension(480, 272));
setTitle("Java Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(path), "UTF-8"));
buf = new StringBuffer();
while (true)
{
String line = reader.readLine();
if (line == null) break;
buf.append(line);
}
final Textimg textimg = new Textimg(buf.toString());
add(textimg);
textimg.setBounds(0, 0, 480, 272);
final javax.swing.Timer timer = new javax.swing.Timer(200, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
textimg.addX(-1);
}
});
timer.setDelay(sleeptime);
timer.start();
}
//----------------------------------------------------------------------
public static void main(String[] args) throws Exception
{
new Banner(args[0]).setVisible(true);
}
}