Java 如何创建动画方法并将其放入绘制方法?我的代码没有';行不通

Java 如何创建动画方法并将其放入绘制方法?我的代码没有';行不通,java,animation,methods,applet,awt,Java,Animation,Methods,Applet,Awt,为什么这样不行?我为两张图片的动画循环创建了一个称为animation()的方法, 我想把它放在绘画方法中。我该怎么做 import java.applet.*; import java.awt.*; public class Slot_Machine extends Applet { Image back; int coin=10; // Place instance variables here public void init () {

为什么这样不行?我为两张图片的动画循环创建了一个称为animation()的方法, 我想把它放在绘画方法中。我该怎么做

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
}
您的
animation()
方法中有一个无限循环,这意味着
paint()
永远不会返回,这会导致尝试启动小程序的线程在等待
paint()
返回时挂起

如果要在后台运行永久循环动画,请尝试在其他线程中运行。看看。

1)为什么要编写小程序?如果是由于老师的特殊要求,请参考。2) 为什么是AWT而不是Swing?关于放弃使用AWT组件的许多好理由,请参见我的答案。不要阻止EDT(事件调度线程)-发生这种情况时,GUI将“冻结”。不要调用
Thread.sleep(n)
为重复任务执行Swing
计时器,或为长时间运行的任务执行
SwingWorker
。有关更多详细信息,请参阅。