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

huangapple go评论64阅读模式
英文:

How to draw image created in try/catch?

问题

I'm learning Java, and I've converted File type into Image using IOException, but how can I use my new Image outside of try/catch?

因为现在 IntelliJ 不识别图像。

英文:

I'm learning Java, and I've converted File type into Image using IOException, but how can I use my new Image outside of 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);
}

Because now IntelliJ does not recognize image.

答案1

得分: 2

在这种情况下,由于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"不存在的错误消息。
  • 通过throws传递异常,通常是更好的解决方案。

根据约定,应使用@Override,因为这样可以捕获拼写错误,例如public void paintComponent(Graphics2D g)public void painComponent(Graphics g)

英文:

In this case - as paintComponent will be called often, and you want to load the image just once, put the image in a field.

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);
    }
}

I have shown two solutions:

  • catching the exception as done now: but one should do something, give an error message to the user that file logo.jpg does not exist
  • passing the exception on by throws, often the better solution.

The convention is to use @Override as this catches typos like public void paintComponent(Graphics2D g) or public void painComponent(Graphics g).

huangapple
  • 本文由 发表于 2020年8月14日 02:49:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63401460.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定