首页 > java > 在Java Applet中连续绘制图像

在Java Applet中连续绘制图像 (Drawing images continuously in Java Applet)

问题

我试图在Applet上绘制大约100个图像。当我这样做时,由于过程太快,我无法查看图像。所以我添加了睡眠功能,这样我就可以在从一个图像转换到另一个图像之间暂停。但这种做法异常。我看不到任何照片,我认为睡眠会一次又一次地被召唤。请帮忙。
这是我的代码:

public class Test extends Applet
{
public void init()
{

    setSize(1000,1000);


}

public void make(Graphics g,int i)
{


}
public void paint(Graphics g)
{
    int i=0;
    for(i=0;i<100;i++)
    {
        if(i!=65)
        {
            Image img = getImage(getDocumentBase(), "abc"+i+".png");
            g.drawImage(img, 0, 0, this);
            try
            {
                Thread.sleep(1000);
            }
            catch(Exception exception)
            {

            }
        }
    }

}

}

现在你可以看到我有0到99的图像,我希望它们在我的Applet窗口上,并且在显示图像后1秒延迟应该存在。但这种情况并非如此。请帮忙

解决方法

sleep将冻结EDT(事件调度线程)。由于Swing是单线程框架,任何阻塞(如睡眠)的东西都会阻止EDT运行,因为它paint是从EDT上下文中调用。不要使用睡眠,Timer而是使用。

另外要注意,这是不好的做法,以catch一个例外,而不是处理它。这将隐藏代码中可能出现的严重意外事件,至少打印错误消息。

问题

I am trying to draw about 100 images on the Applet. When i did that I was not able to look at an image as the process was too fast. So I added sleep function so that I can give a pause between transition from one image to another. But that worked abnormally. I could not see any pictures and I think the sleep is getting called again and again. Please help.
Here is my code:

public class Test extends Applet
{
public void init()
{

    setSize(1000,1000);


}

public void make(Graphics g,int i)
{


}
public void paint(Graphics g)
{
    int i=0;
    for(i=0;i<100;i++)
    {
        if(i!=65)
        {
            Image img = getImage(getDocumentBase(), "abc"+i+".png");
            g.drawImage(img, 0, 0, this);
            try
            {
                Thread.sleep(1000);
            }
            catch(Exception exception)
            {

            }
        }
    }

}

}

Now you can see I have images from 0 to 99 and I want them on my Applet window and after an image is displayed 1 sec delay should be there. But this is not the case. Please help

解决方法

sleep will freeze the EDT (Event Dispatching Thread). Since Swing is single threaded framework, anything that blocks (like sleep), prevents the EDT from running since paint is called from the context of the EDT. Don't use sleep, use Timer instead.

Another note, it's bad practice to catch an exception and not handling it. This will hide serious unexpected things that might occur in your code, at least print the error message.

相似信息