我在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中的某些设置?
我还在paintComponent方法中添加了一些测试代码,如下所示:
protected void paintComponent( Graphics g ) { System.out.println( "paintComponent call number: " + counter ); ++counter; super.printComponent( g ); ball.draw( g ); }
在类MovingBall中声明的变量计数器初始值为0.我观察到每秒paintComponent的调用次数远远超过JPanel的实际刷新率.