使用JFrame创建动画



我在创建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
}
}

最新更新