英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论