私はUbuntu 14.4.1でシンプルなJavaアニメーションプログラムを作成しました。 JPanelの中を動くボール。しかし、実行時には、ボールはJPanelでかなり不自然に動きます。この問題は、マウスをJPanelの内部に移動するまで続きます。 JPanelの中でマウスを動かすとき、ボールの動きは非常に滑らかです。私はWindows 10でこのプログラムを実行したと言わなければならず、問題は発生しませんでした。私のプログラムのコードは次の通りです:Linuxでジャーキーを実行する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でいくつかの設定を変更する必要がありますか?
protected void paintComponent(Graphics g) {
System.out.println("paintComponent call number: " + counter);
++counter;
super.printComponent(g);
ball.draw(g);
}
をクラスMovingBallで宣言さ0の変数カウンタ初期値を次のように は、私はまた、paintComponentメソッド内でいくつかのテストコードを入れています。 paintComponentの1秒あたりの呼び出し数は、実際のJPanelのリフレッシュレートよりもはるかに多いことがわかりました。
paintComponentメソッド内のprintlnが遅くなり、目に見える効果がある可能性があります。あなたはそこから出たいと思うでしょう。 –
printlnを追加する前に主な問題が発生しました。 printlnステートメントは、その問題の詳細を調べるためのテストステートメントです。 – Hedayat
また、アニメーションメソッド内でリアルタイムインクリメントを取得し、リアルタイムインクリメントに基づいてスプライトの最適な位置を計算します。この方法では、アニメーションが速くても遅い場合でも、ボールは同じ距離を移動します。 –