-3

So I know to declare and initialize a global variable one would have to do something like this for example:

public static int Variable = 2;

But I want to know if there is a way to initialize a global BufferedImage variable with an image from a file. I can't use the above code, since I also need to include a try/catch statement.

Anyone have any solutions to my problem?

BOTK
  • 11
  • 3

1 Answers1

0

I think that you want to use a static bloc.

 public static BufferedImage image = null ;

 static
     {
     try {
         image = javax.imageio.ImageIO.read(new File("Image path")) ; // Or whatever reader you use.
         }
     catch (IOException ex)
         {
         Logger.getLogger(Prototyper.class.getName()).log(Level.SEVERE, null, ex);
         }
     }

Btw, as mentioned in the first comment below, this is REALLY bad practice. Usually you want to use a Read static method, and you read the image where you need it, not by default.

FiReTiTi
  • 5,597
  • 12
  • 30
  • 58
  • 1
    Why not just use a static method? Anyway, doing I/O in static initialization is bad practice, and should be avoided. I won't downvote, as it's what the OP asked for, but.. Really, don't do this. :-) – Harald K Sep 22 '16 at 17:49
  • I DO AGREE and I DO NOT DO that either, I just answered the question. I use a static method that read an image when I need it. In his case, he wants to do it by default. I've edited my answer to precise it. – FiReTiTi Sep 22 '16 at 18:50