简体   繁体   English

如何创建动画方法并将其放入绘画方法? 我的代码不起作用

[英]How can I create an animation method and put that in paint method? My code doesn't work

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. 我为两个图片的动画循环创建了一个名为animation()的方法,我想将其放入paint方法中。 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
}

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

If you want to run a forever-looping animation in the background, try doing it in another thread. 如果要在后台运行永久循环的动画,请尝试在另一个线程中执行该动画。 Take a look at ExecutorService . 看看ExecutorService

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM