显示JLabel运动

时间:2013-10-06 14:57:07

标签: java swing animation jlabel event-dispatch-thread

我正在尝试创建一个简单的动画,其中一系列气泡围绕中心点旋转。我有一个版本的动画,其中气泡在它们开始旋转之前从中心点扩散,这很好,但是当我点击其中一个图像(激发动画)时,屏幕会冻结片刻,然后气泡出现在他们的最终位置,而不是展示他们所做的每一步。

到目前为止我所拥有的是:

    while(bubble[1].getDegree() != 270) 
    { 
        long time = System.currentTimeMillis(); 

        //the below if statement contains the function calls for
        //the rotating bubble animations.
        next();
        draw();

        //  delay for each frame  -   time it took for one frame 
        time = (1000 / fps) - (System.currentTimeMillis() - time); 

        if (time > 0) 
        { 
            try 
            { 
                Thread.sleep(time); 
            } 
            catch(Exception e){} 
        }
    }


public void draw()
{
    for(int i = 1; i < bubble.length; i++)
    {   
        iconLabel[i].setLocation(bubble[i].getX(), bubble[i].getY());
        textLabel[i].setLocation((bubble[i].getX()+10),(bubble[i].getY()+10));
    }

}

为了清楚起见,方法“next()”只是将气泡的位置改变到适当的位置,我知道这是因为我之前有动画工作但是一旦我将动画实现到JLabels它就停止了工作

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

图形被冻结,因为您阻止了事件派发线程。绘图在与while循环相同的线程中完成,并且由于循环可以防止在其运行时发生任何其他事情,因此只有在循环结束后,swing才能进行绘制,因此只绘制最后一个位置。

使用摆动Timer代替:

timer = new Timer(delay, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // whatever you need for the animation
        updatePositions();
        repaint();
    }
});
timer.start();

然后在处理完所需的所有帧时调用timer.stop()