如何绘制在 try/catch 中创建的图像?

How to draw image created in try/catch?

我正在学习 Java,我已经使用 IOExceptionFile 类型转换为 Image,但是我如何使用我的新 Image ] 在 try/catch 之外?

try {
        File obraz = new File("C:\Users\ender\Pictures\logo.jpg");
        Image image = ImageIO.read(obraz);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage(image);
}

因为现在 IntelliJ 不识别图像。

在这种情况下 - 因为 paintComponent 会经常被调用,而您想只加载一次图像,请将图像放在一个字段中。

private Image image;

...() {
    try {
        File obraz = new File("C:\Users\ender\Pictures\logo.jpg");
        image = ImageIO.read(obraz);
    } catch (IOException ex) {
         ex.printStackTrace();
    }
}

...() throws IOException {
    File obraz = new File("C:\Users\ender\Pictures\logo.jpg");
    image = ImageIO.read(obraz);
}

@Override
public void paintComponent(Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    if (image != null) {
        g2.drawImage(image);
    }
}

我已经展示了两个解决方案:

  • 像现在一样捕获异常:但是应该做点什么,给用户一条错误消息,文件 logo.jpg 不存在
  • 通过抛出传递异常,通常是更好的解决方案。

惯例是使用 @Override,因为这样可以捕获 public void paintComponent(Graphics2D g)public void painComponent(Graphics g).

等拼写错误