我有一个非常简单的动画,一个大字体的文字不断(逐个像素)移动到左边.首先将文本转换为图像,然后启动定时器任务,重复(每10-20 ms)将图像的x坐标递减1,并进行重绘().
这个程序在某些系统上显示出一个奇怪的行为.在带有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,4800,272); gr.setColor(new Color(135,175,0)); gr.drawString(str,ytext); gr.dispose(); } g.drawImage(img,x,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,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); } }
解决方法
@H_502_13@ 完成绘图后,尝试调用此方法:Toolkit.getDefaultToolkit().sync();
这会刷新一些像Linux这样的系统的图形缓冲区.参见Javadoc:http://docs.oracle.com/javase/7/docs/api/java/awt/Toolkit.html#sync()