【问题标题】:How to draw an image on the applet如何在小程序上绘制图像
【发布时间】:2014-07-06 00:39:30
【问题描述】:
public class ImageExample2 extends Applet
{

    BufferedImage bi;


    public void init ()
    {

        resize (500, 500);

        try
        {

            BufferedImage bi = ImageIO.read (new File ("G:\\Java\\WhatDotColour\\Pacman.PNG"));
        }
        catch (java.io.IOException e)
        {
            e.printStackTrace ();
        }
    }


    public void paint (Graphics g)
    {

        g.drawImage (bi, 20, 140, this); //.drawImage(in, 0, 0, null);

    }
}

每次我尝试运行它时,它都会给我一个空指针异常。我该如何解决?

【问题讨论】:

  • 使 bi 成为类变量(即全局)
  • 我是 Java 新手,所以我不知道该怎么做
  • 其实已经是了,看我的回答...
  • 实例变量根本没有初始化。

标签: java awt paint bufferedimage


【解决方案1】:

不要AppletFile 混用。它们就像油和水。 Applet 在浏览器中运行。始终使用相对路径。

使用 Applet#getCodeBase() 获取基本 URL。这是包含此小程序的目录的 URL。

示例代码:(查看getCodeBase()方法的输出并修改图片路径)

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;

public class ImageExample2 extends Applet {

    private Image bi;

    public void init() {

        resize(500, 500);

        System.out.println(getCodeBase()); // file:/D:/Workspace/JavaProject/bin/

        // This the actual code that should be used to read the image in Applet
        bi = getImage(getCodeBase(), "images/222.png");
    }

    public void paint(Graphics g) {
        g.drawImage(bi, 20, 140, this);

    }
}

如果您使用的是 Windows 和 Eclipse IDE,请查看下面显示的屏幕截图以获取上述示例代码图像路径。

【讨论】:

    【解决方案2】:

    变化:

    BufferedImage bi=ImageIO.read (new File ("G:\\Java\\WhatDotColour\\Pacman.PNG"));
    

    bi = ImageIO.read (new File ("G:\\Java\\WhatDotColour\\Pacman.PNG"));
    

    改变

    g.drawImage (bi, 20, 140, this); //.drawImage(in, 0, 0, null);
    

    if (bi!=null) g.drawImage (bi, 20, 140, this); //.drawImage(in, 0, 0, null);
    

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 2012-04-20
      • 2011-11-11
      相关资源
      最近更新 更多