JAVA弹跳球很冷

时间:2016-01-31 14:25:29

标签: java swing

我用Java创建了弹跳球应用程序。一切都按照假设运作,但球在移动时会冻结。当我将光标移动到窗口时,球正在平滑移动。当我停止移动光标时,它再次冻结。

操作系统:Fedora 23 JDK:8

public class Main {
public static void main(String[] args) {
    Game game = new Game();
}
}

class Game extends JFrame {

public Game(){
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    Ball ball1 = new Ball();
    add(ball1);
    setSize(400,300);
    setTitle("Bubbles");
    setVisible(true);
}

}

class Ball extends JPanel implements Runnable{
int radius = 50;
int x = 5 ;
int y = 5;
int dx = 2;
int dy = 2;

public Ball (){
    Thread thread = new Thread(this);
    thread.start();
}


@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.red);
    g.fillOval(x,y,radius,radius);
}

public void moveBall (){

    if (x + dx > 400 - radius){
        x = 400 - radius;
        dx = -dx;
    } if (x + dx < 0){
        x = 0;
        dx = -dx;
    }
    else {
        x += dx;
    }

    if (y + dy > this.getHeight() - radius){
        y = this.getHeight() - radius;
        dy = -dy;
    } if (y + dy < 0){
        y = 0;
        dy = -dy;
    }
    else {
        y += dy;
    }

}


@Override
public void run() {
    while (true){
        moveBall();
        repaint();
        try {
            Thread.sleep(17);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
}

1 个答案:

答案 0 :(得分:2)

代码有效,但在Swing中使用Thread并不是最好的方式Concurrency in Swing

在你的情况下,摆动Timer会更合适。

示例

javax.swing.Timer timer = new javax.swing.Timer(17, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        ball1.runMe();
    }
});
timer.start();

runMe方法与您当前的run方法类似,只需删除whileThread.sleep

public void runMe() {
    moveBall();
    repaint();  
}

当然,您的Ball将不再实施Runnable,因此您删除所有线程代码