0

I am trying to add an image to a JPanel

package testing;

import java.io.*;
import java.util.*;
import java.security.*;
import javax.xml.bind.DatatypeConverter;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;


public class Testing extends JPanel 
{        
    public static void main(String[] args) 
    {
        BufferedImage myPicture;           
        try
        {    
             myPicture = ImageIO.read(new File("./src/testing/cal.png"));
        }
        catch (IOException ex) {
            // handle exception...
        }
        JLabel picLabel = new JLabel(new ImageIcon(myPicture));//error is here            
        Testing t = new Testing();
        t.add(picLabel);    
    }
}

I get the following error

 variable myPicture might not have been initialize

I thought i already initialise myPicture with the following line

 myPicture = ImageIO.read(new File("./src/testing/cal.png"));

It seems I am wrong about it , how do i resolve this error so that I can add a image to a JPanel

Community
  • 1
  • 1
Computernerd
  • 7,378
  • 18
  • 66
  • 95
  • By the time of deployment, those resources will likely become an [tag:embedded-resource]. That being the case, the resource must be accessed by `URL` instead of `File`. See the [info page](http://stackoverflow.com/tags/embedded-resource/info) for the tag, for a way to form an `URL`. – Andrew Thompson Apr 21 '14 at 08:24

2 Answers2

1
BufferedImage myPicture = null;
Michał Tabor
  • 2,441
  • 5
  • 23
  • 30
1

You initialize it inside the try block, you have to give it some arbitrary value outside the try block, like null, so the compiler knows the value is always initialized, even if the try fails.

Harry Blargle
  • 416
  • 2
  • 11
  • 18