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

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

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?

  1. try {
  2. File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
  3. Image image = ImageIO.read(obraz);
  4. } catch (IOException ex) {
  5. ex.printStackTrace();
  6. }
  7. }
  8. public void paintComponent(Graphics g){
  9. Graphics2D g2 = (Graphics2D) g;
  10. g2.drawImage(image);
  11. }

Because now IntelliJ does not recognize image.

答案1

得分: 2

在这种情况下,由于paintComponent经常被调用,而您希望只加载一次图像,因此将图像放入字段中。

  1. private Image image;
  2. ...() {
  3. try {
  4. File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
  5. image = ImageIO.read(obraz);
  6. } catch (IOException ex) {
  7. ex.printStackTrace();
  8. }
  9. }
  10. ...() throws IOException {
  11. File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
  12. image = ImageIO.read(obraz);
  13. }
  14. @Override
  15. public void paintComponent(Graphics g){
  16. Graphics2D g2 = (Graphics2D) g;
  17. if (image != null) {
  18. g2.drawImage(image);
  19. }
  20. }

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

  • 如现在所做的那样捕获异常:但应该执行一些操作,向用户提供文件"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.

  1. private Image image;
  2. ...() {
  3. try {
  4. File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
  5. image = ImageIO.read(obraz);
  6. } catch (IOException ex) {
  7. ex.printStackTrace();
  8. }
  9. }
  10. ...() throws IOException {
  11. File obraz = new File("C:\\Users\\ender\\Pictures\\logo.jpg");
  12. image = ImageIO.read(obraz);
  13. }
  14. @Override
  15. public void paintComponent(Graphics g){
  16. Graphics2D g2 = (Graphics2D) g;
  17. if (image != null) {
  18. g2.drawImage(image);
  19. }
  20. }

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:

确定