0

Why doesn't this work? I created a method for an animation loop of two pictures called animation(), and i want to put that in the paint method. How do i do this?

import java.applet.*;
import java.awt.*;

public class Slot_Machine extends Applet
    {
    Image back;
    int coin=10;
    // Place instance variables here

    public void init ()
    {
        back= getImage(getDocumentBase(),"Images/Background/Slot Machine.png");
        // Place the body of the initialization method here
    } // init method

    public void animation(Graphics g)
    {
    Image Title1,Title2;
    Title1= getImage(getDocumentBase(),"Images/Title Animation/Title 1.png");
    Title2= getImage(getDocumentBase(),"Images/Title Animation/Title 2.png");
    while(true){
    g.drawImage(Title2,200,0,this);
    { try { Thread.currentThread().sleep(2000); } 
                catch ( Exception e ) { } }
    g.drawImage(Title1,200,0,this);
    { try { Thread.currentThread().sleep(2000); } 
                catch ( Exception e ) { } }
    }//end while(true) loop
    }//end animation

    public void paint (Graphics g)
    {   
        g.drawImage(back,0,0,this);
        animation(); //FROM THE METHOD ABOVE, WHY DOESNT THIS WORK? HOW DO I FIX THIS?
        String coins  = String.valueOf(coin);
        g.setColor(Color.white);
        g.setFont(new Font("Impact",Font.PLAIN,30));
        g.drawString(coins,405,350);
        // Place the body of the drawing method here
    } // paint method
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson Apr 21 '14 at 08:27
  • Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling `Thread.sleep(n)` implement a Swing `Timer` for repeating tasks or a `SwingWorker` for long running tasks. See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details. – Andrew Thompson Apr 21 '14 at 08:28

1 Answers1

1

Your animation() method has an infinite loop in it, which means that paint() never returns, which is causing the thread trying to start up the applet to hang while waiting for paint() to return.

If you want to run a forever-looping animation in the background, try doing it in another thread. Take a look at ExecutorService.

azurefrog
  • 10,785
  • 7
  • 42
  • 56