Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I took this code straight out of 'Java all in one for Dummies' ....why doesn't it work?

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


@SuppressWarnings("serial")
public class Picture extends JFrame{

    public static void main(String[] args){

        new Picture();

    }

    public Picture(){

        this.setTitle("Picture");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new JPanel();
        ImageIcon pic = new ImageIcon("TestImage.jpg");
        p.add(new JLabel(pic));
        this.add(p);
        this.pack();
        this.setVisible(true);
        System.out.println(pic);
    }

}

This code as it is just displays a collapsed frame. I would expect that the pack(); method call would size the frame around my .jpg image, correct?

I can already hear the first question, and yes the image is in the same folder as my project package folder.

I am using the Eclipse IDE.

I also added the println(); statement to see what the Image reference returned and it returns "TestImage.jpg". I thought it would return an address of the image in memory.??

I have been reading the forum all morning and I can't really find anything that helps me there without copying and using someone else's more complex code. I am trying to keep this as simple as I can so that I don't confuse myself.

Thanks in advance for any help.

like image 441
Abstraction is everything. Avatar asked Dec 20 '22 18:12

Abstraction is everything.


1 Answers

Try:

ImageIcon image = new ImageIcon(getClass().getResource("TestImage.jpg"));

See How to Use Icons tutorial for more details, in particular Loading Images Using getResource section.

like image 94
tenorsax Avatar answered Dec 24 '22 01:12

tenorsax