Java 使用JFrame创建动画

Java 使用JFrame创建动画,java,swing,animation,Java,Swing,Animation,我在创建Java框架应用程序时遇到了一个问题。 我不能在循环中调用组件的重绘; 这是mo类的一部分: if(e.getSource()==drop){ //check if the row has space if(currentGame.isFull(choosePosition)){ return; } else{ int row = currentGame.placeFigure(choosePosition, tu

我在创建Java框架应用程序时遇到了一个问题。 我不能在循环中调用组件的重绘; 这是mo类的一部分:

if(e.getSource()==drop){
    //check if the row has space
    if(currentGame.isFull(choosePosition)){
        return; 
        }
    else{
        int row = currentGame.placeFigure(choosePosition, turn);

        ImageIcon temp;
        if(turn)
            temp = firstIcon;
        else
            temp = secondIcon;
        for(int i = 0; i != row + 1; ++i){
            cells[i][choosePosition].setIcon(temp);
            if(i != 0)
                cells[i - 1][choosePosition].setIcon(emptyIcon);
            gameBoardPanel.repaint();
            gameBoardPanel.revalidate();
            Graphics myGraphics = getGraphics();
            // Draw as appropriate using myGraphics
            myGraphics.dispose();
            paint(myGraphics);
            try {
                  Thread.sleep(500);
                } catch (InterruptedException ie) {
                    //Handle exception
                    System.out.println("can't start animation");
                }
        }
        repaint();
    }
}

开始学习如何使用paintComponent方法。下面是如何使用计时器:

public class your_class_name extends if_you_need_to_extend implments ActionListener
{

//In the constructor...

    Timer t = new Timer(milliseconds,this);
    t.start();

//In the main class...

@Override
public void actionPerformed(ActionEvent e)
{
    //animations here
    repaint(); //calls paintComponent again
}

@Override
public void paintComponent(Graphics g)
{
    //default drawings here
}
}

不要在帧中创建动画,而是创建
JPanel
BufferedImage
。1) 为了更快地获得更好的帮助,请发布一个。2) 例如,获取图像的一种方法是热链接到中看到的图像。不要阻止事件调度线程。取而代之的是使用javax.swing.TimerAlso,不要使用getGraphics(如果使用了,也不要处理它),这不是绘制的方式。看一看更多的细节,我意识到它使用睡眠:)我的问题对你不起作用吗?