0

How can I do a similar drop down animation on gridlayout?

I'm trying to do the game Connect 4 with swing lib.

Why this doesn't work?

private class ButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
        JButton bottone = event.getSource();
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                if (bottone == Grid[i][j]) {
                    animation(i, j);
                    Grid[i][j].setBackground(new Color.RED);
                    Grid[i][j].setEnabled(false);
                    if (i > 0) {
                        Grid[(i - 1)][j].setEnabled(true);
                    }
                }
            }

        }
    }
}

private void animation(int row, int column) {
    try {
        for (int i = 0; i < row; i++) {
            Grid[i][column].setBackground(new Color.RED);
            revalidate();
            repaint();
            Thread.sleep(100);
            Grid[i][column].setBackground(new Color.WHITE);
            revalidate();
            repaint();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Is it possible do something like this?

Razib
  • 10,965
  • 11
  • 53
  • 80

1 Answers1

0

Unfortunately revalidate() and repaint() don't actually get rendered until after the entire method call ends. You are going to have to use a timer of some sort if you want to create animation. Here is something similar in a different SO question how to use a swing timer to start/stop animation

Try as long as timer is running it should be calling repaint at 60 fps

Timer timer;
timer = new Timer(33, new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
    // change polygon data
    // ...

    repaint();
}
});
timer.start();
Community
  • 1
  • 1