如何将图像保留在屏幕上?

时间:2014-05-18 02:47:21

标签: java applet

import java.applet.Applet;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.URL;
import javax.imageio.*;
import java.awt.Component;

public class ImageExample3 extends Applet
{
private BufferedImage img;

int counter = 0;
private BufferedImage next2;
Point lll;
public void init ()
{
    resize (500, 500);
    try
    {
        URL url = new URL (getCodeBase (), "Pacman.png");
        img = ImageIO.read (url);
    }
    catch (IOException e)
    {
    }
    repaint ();
}


public void paint (Graphics g)
{
    if (counter == 0)
    {
        g.drawImage (img, 0, 0, null);
        Dimension appletSize = this.getSize ();
        lll = getLocationOnScreen ();
        try
        {
            next2 = new Robot ().createScreenCapture (new Rectangle (lll.x, lll.y, 500, 500));
        }
        catch (java.awt.AWTException e)
        {
        }
        g.drawImage (next2, 0, 0, null);
        System.out.println (lll);
        counter++;
    }
}

}

我想要做的是加载图片然后绘制它,然后在paint方法中,我用一个点来告诉我applet窗口在屏幕上的位置并截取它的截图然后在applet上绘制它。但是,我希望这只发生一次,所以我添加了一个计数器,但每当我运行它时,它会绘制图像然后被白色框取代。我该怎么做才能解决它?

1 个答案:

答案 0 :(得分:0)

屏幕不断需要刷新。要显示图形,它会在每次屏幕刷新时通过调用update方法绘制图像。更新方法通过将其绘制为白色来清除屏幕。然后,update方法根据上下文调用paint方法(或repaint)。

因为您只绘制一次图形,所以您的图形会被空白屏幕绘制而不会刷新。您需要在屏幕刷新的每个时间绘制图形,否则它们将被删除。

始终绘画,但只拍摄一次屏幕截图。这是绘画方法的一个例子:

public void paint (Graphics g)
{

    g.drawImage (img, 0, 0, null);
    Dimension appletSize = this.getSize ();
    lll = getLocationOnScreen ();

    if (counter == 0) //try taking the screenshot when counter is 0
    {
        try
        {
             next2 = new Robot ().createScreenCapture (new Rectangle (lll.x, lll.y, 500, 500));
        }
        catch (java.awt.AWTException e) {}
    }
    if (next2 != null) //if you took the screenshot and saved it to next2, draw it
        g.drawImage (next2, 0, 0, null);
    System.out.println (lll);
    counter++;
}