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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With