在Linux中运行jerky的Java Animation程序
发布时间:2020-12-14 01:07:15 所属栏目:Linux 来源:网络整理
导读:我在Ubuntu 14.4.1中编写了一个简单的 Java动画程序.一个球在JPanel内移动.但在执行时,球在JPanel中变得非常生涩.这个问题一直持续到我在JPanel中移动鼠标为止.在JPanel内移动鼠标时,球的运动非常顺畅.应该说我在Windows 10中运行了这个程序,并没有出现问题.
我在Ubuntu 14.4.1中编写了一个简单的
Java动画程序.一个球在JPanel内移动.但在执行时,球在JPanel中变得非常生涩.这个问题一直持续到我在JPanel中移动鼠标为止.在JPanel内移动鼠标时,球的运动非常顺畅.应该说我在Windows 10中运行了这个程序,并没有出现问题.我的程序代码如下:
import java.awt.*; import javax.swing.*; public class BouncingBall extends JPanel { Ball ball = new Ball(); void startAnimation() { while( true ) { try { Thread.sleep( 25 ); ball.go(); repaint(); } catch( InterruptedException e ) {} } // end while( true ) } // end method startAnimation() protected void paintComponent( Graphics g ) { super.paintComponent( g ); ball.draw( g ); } // end method paintComponent // inner class Ball class Ball { int x; int y; int diameter = 10; int xSpeed = 100; int ySpeed = 70; void go() { x = x + (xSpeed*25)/1000; y = y + (ySpeed*25)/1000; int maxX = getWidth() - diameter; int maxY = getHeight() - diameter; if( x < 0 ) { // bounce at the left side x = 0; xSpeed = -xSpeed; } else if( x > maxX ) { // bounce at the right side x = maxX; xSpeed = -xSpeed; } else if( y < 0 ) { // bounce at the top side y = 0; ySpeed = -ySpeed; } else if( y > maxY ) { // bounce at the bottom size y = maxY; ySpeed = -ySpeed; } // end if-else block } // end method go() void draw( Graphics g ) { g.fillOval( x,y,diameter,diameter ); } // end method draw } // end inner class Ball public static void main( String[] args ) { JFrame window = new JFrame(); window.setDefaultCloSEOperation( JFrame.EXIT_ON_CLOSE ); BouncingBall animation = new BouncingBall(); animation.setPreferredSize( new Dimension( 500,500 ) ); animation.setBackground( Color.white ); window.add( animation ); window.pack(); window.setVisible( true ); animation.startAnimation(); } // end method main } // end class BouncingBall 问题是什么?我是否必须更改Ubuntu中的某些设置? protected void paintComponent( Graphics g ) { System.out.println( "paintComponent call number: " + counter ); ++counter; super.printComponent( g ); ball.draw( g ); } 在类MovingBall中声明的变量计数器初始值为0.我观察到每秒paintComponent的调用次数远远超过JPanel的实际刷新率. 解决方法
Windows中默认启用视频加速,但在Linux中默认不启用. (这已经存在多年了;我可以发誓这个默认值已经针对最近的Java版本进行了更改,但显然我错了.)
你可以enable OpenGL获得加速的性能: public static void main( String[] args ) { System.setProperty("sun.java2d.opengl","true"); JFrame window = new JFrame(); 或者,您可以在命令行上设置属性: java -Dsun.java2d.opengl=true BouncingBall (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |