我在Ubuntu 14.4.1中編寫了一個簡單的Java動畫程序。在JPanel內移動的球。但在執行過程中,JPanel中的球移動得相當不平穩。直到我將鼠標移動到JPanel中,這個問題纔會繼續。在JPanel內部移動鼠標時,球的運動非常平滑。應該說,我已經在Windows 10中運行該程序,並沒有發生任何問題。我的程序代碼如下:在Linux中運行JERKY的Java動畫程序
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實際刷新率。
您的paintComponent方法中的println會減慢速度,並且可能會有明顯的效果。你會希望它離開那裏。 –
添加println之前出現的主要問題。 println聲明僅僅是一個測試語句,可以詳細瞭解這個問題。 – Hedayat
我也會在你的動畫方法中獲得實時增量,並根據實時增量計算精靈的最佳位置。這樣,如果動畫快或慢,球就會移動相同的距離。 –