Hed*_*our 6 java linux ubuntu animation swing
我在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
Run Code Online (Sandbox Code Playgroud)
问题是什么?我是否必须更改Ubuntu中的某些设置?我还在paintComponent方法中添加了一些测试代码,如下所示:
protected void paintComponent( Graphics g ) {
System.out.println( "paintComponent call number: " + counter );
++counter;
super.printComponent( g );
ball.draw( g );
}
Run Code Online (Sandbox Code Playgroud)
在类MovingBall中声明的变量计数器初始值为0.我观察到每秒paintComponent的调用次数远远超过JPanel的实际刷新率.
Windows中默认启用视频加速,但在Linux中默认不启用.(这已经存在多年了;我可以发誓这个默认值已经针对最近的Java版本进行了更改,但显然我错了.)
您可以启用OpenGL以获得加速的性能:
public static void main( String[] args ) {
System.setProperty("sun.java2d.opengl", "true");
JFrame window = new JFrame();
Run Code Online (Sandbox Code Playgroud)
或者,您可以在命令行上设置属性:
java -Dsun.java2d.opengl=true BouncingBall
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
607 次 |
| 最近记录: |