0

I know that this question has been asked many times in a similar way on this platform. I've already spent a few hours trying the answers on my code (Threats and much more), but nothing has worked for me so far. So I'll ask the question here again specifically for my situation. I am currently programming a card game and would like to flip a coin before a card is played. I have already animated this as a gif and the coin toss logic works too. Now I want to get the animation into my program. For this I wrote a while loop which runs for 2 seconds. In this I would like to repaint, but the paint method (like many others had the problem before) is not called. This is my code in my public boolean cointoss() method for it:

cointossed = true;
long startTime = System.currentTimeMillis();
long elapsedTime = 0L;

while (elapsedTime < 2*1000) {
    //Used this beacuse I thought my PC isnt fast enough
    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
            
    paintImmediately();
    elapsedTime = (new Date()).getTime() - startTime;
    }
cointossed = false;

In my paint() method there is the following Code, to draw the gif:

if(cointossed) {
    g.drawImage(gif, 20, 20,100 , 100, null);
}

Somebody has an idea for my specific case?

Earny
  • 1
  • 1
  • Simply use a Swing Timer. Set cointossed to true, start to the Timer with a 2 second delay, when triggered, reset cointossed (and don’t forget to call repaint) – MadProgrammer Jun 02 '22 at 20:57
  • When calling drawImage, especially for animated gifs, pass an instance of ImageObserver, most Swing components implement ImageObserver, so you’d just need to pass the component through which you’re painting – MadProgrammer Jun 02 '22 at 20:59
  • The other choice is to use your “main loop”, which could check the amount of time tree cointoss has been running – MadProgrammer Jun 02 '22 at 21:00
  • 1
    Side note: why are you resorting to `(new Date()).getTime()` when you have demonstrated knowledge about `System.currentTimeMillis()` at the beginning of the method? – Holger Jun 03 '22 at 09:22

1 Answers1

0

Thx to MadProgrammer for helping me out with this. I dont know if you mean it like that, but this worked for me:

ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            System.out.println("Timer abgeschlossen");
            cointossed = false;
           repainter.setRepeats(false);
        }
    };
    ActionListener rep = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            repaint();
           
        }
    };
    Timer timer = new Timer(2000 ,taskPerformer);
    Timer repainter = new Timer(20 ,rep);

With this I created my own while loop where I can call repaint(); Just started both timers and my gif plays :D

Earny
  • 1
  • 1