Ivy
Ivy

Reputation: 511

Cannot set imageicon to JLabel, always get null

I am new to swing and trying to write a code that have a button on JFrame and click it can open a JFileChooser to choose an image, after user choose, it will display it on thr JFrame, but I keep getting a
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
and I found that I cannot set the selected image icon to the JPanel, this drives me crazy, help me please!!!
My code is:

public class ImageLoading extends JFrame{

private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIFHT = 500;
private BufferedImage mImage;
private JFrame frm;
private JPanel panel;
private JButton button;
String name,name1;

public class ButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent event){
        String source=filechoose();
        File inputFile = new File(source);
        System.out.println("File Directory: " + inputFile.toString());
        try {
            mImage = ImageIO.read(inputFile);
            System.out.println("Buffered Image: " + mImage.toString());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }

            ImageIcon image =  new ImageIcon(mImage);
            System.out.println("Image Icon: " + image.toString() + " :::  " +image.getIconHeight());
            JLabel lb = new JLabel(image);// HERE I GET EXCEPTION
            System.out.println("Image Label: " + lb.toString());
            panel.add(lb);
            panel.revalidate();
            panel.repaint();
            frm.pack();

    }
}


public void imageLoading(){
    frm = new JFrame("image loading test");
    frm.setLayout(null);
    JLabel label2 = new JLabel("Open a picture");
    button = new JButton("Open");
    panel = new JPanel();
    panel.setBounds(10, 10, 400, 400);

    panel.add(button);
    panel.add(label2);

    ImageLoading load = new ImageLoading();
    ButtonListener listener = load.new ButtonListener();

    button.addActionListener(listener);

    frm.add(panel);

    frm.setSize(FRAME_WIDTH,FRAME_HEIFHT);
    frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frm.setVisible(true);
}

public String filechoose(){
    JFileChooser chooser = new JFileChooser();

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public boolean accept(File f) {
            name = f.getName().toLowerCase();
            return name.endsWith(".gif") || name.endsWith(".jpg")
                    || name.endsWith(".jpeg") || f.isDirectory();
        }

        public String getDescription() {
            return "Image files";
        }
    });

    int r = chooser.showOpenDialog(this);

    if (r == JFileChooser.APPROVE_OPTION) {
        name1 = chooser.getSelectedFile().getAbsolutePath();
        StringBuffer sb=new StringBuffer();
        sb.append(name1);

        int l=sb.length();
        for(int i=0;i<l;i++){
            if(sb.charAt(i)=='\\'){
                sb.insert(i, "\\");                 
            }
        }
    }
    return name1;
}

public static void main(String a[]){

    ImageLoading i = new ImageLoading();
    i.imageLoading();
}

` Please help me with this or give me some sample doing this....thanks!

Upvotes: 0

Views: 419

Answers (1)

Reimeus
Reimeus

Reputation: 159754

Look at these lines:

ImageLoading load = new ImageLoading(); // not needed
ButtonListener listener = load.new ButtonListener();
button.addActionListener(listener);

You are adding a ButtonListener to your button attached to an new (and unnecessary) instance of ImageLoading. panel is instantiated in the imageLoading method, but this isn't called in this new instance resulting in the NullPointerException later on when you attempt to call

panel.add(lb);

(The stacktrace is a good indicator of the root cause of an NPE)

You can use the current instance of ImageLoading that has panel instantiated:

ButtonListener listener = new ButtonListener();

Upvotes: 1

Related Questions