2

我正在尝试使用在我正在编写的应用程序中getImage()显示图像。JPanel我已经尝试并试图让它为我工作,最终发现即使路径完全不正确,它仍然不起作用,也不会NullPointerException按预期返回。

Image i;    

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(i, 0, 0, 200, 200, this);
} // end paintComponent();

public Pnl() {
    super();
    setBackground(Color.GREEN);
    setBorder(BorderFactory.createLineBorder(Color.GRAY, 10));
    i = Toolkit.getDefaultToolkit().getImage("shrek.jpg");
} // end constructor    

当我使用诸如“shrek...jdhhd”getImage()之类的参数运行代码时,它会执行完全相同的操作。

4

2 回答 2

3

我正在尝试使用 getImage() 在

当您发布问题时,如果您需要帮助,请发布适当的SSCCE,否则我们会花时间猜测。

例如,图像可能被正确读取,但问题是面板的大小为 (0, 0),因此没有可绘制的内容。

您还应该重写该getPreferredSize()方法以返回 (200, 200) 的 Dimension,因为这是您要绘制图像的大小。

如果没有显示如何使用此面板的上下文的 SSCCE,我们只是在猜测。

于 2013-10-20T03:24:32.413 回答
2

有几种不同的方式可以读取图像。

  1. 通过使用ImageIcon然后从中提取Image
  2. 使用ImageIO

我怀疑你的图像路径有问题。尝试这个:

Path imgPath = Paths.get("/path/to/image.png");
if(Files.exists(imgPath)){
    // do whatever
} else{

    // incorrect path
}

如果Path确实存在:

ImageIcon imageAsIcon = new ImageIcon(imgPath.getAbsolutePath());
Image imageOfIcon = imageAsIcon.getImage();

现在,您可以检索它的Graphics对象并执行任何操作,可能会将其转换为BufferedImage

您也可以尝试ImageIO如下使用:

BufferedImage img;

try {
    URL url = new URL(new File("/path/to/image.png");
    img = ImageIO.read(url);
} catch (IOException e) {
}
于 2013-10-20T02:59:48.370 回答