Archie Archie - 2 months ago 6
Java Question

Java - Adding Photo to JFrame

For a school project I need to create a GUI and do some things with it, one of the things is adding an

ImageIcon
to my
JFrame
.

public static void main(String[] args) {
String path = "Users\Archie King\Desktop\School\Computer Science\cat.png";
JFrame frame = createFrame(new Animal("Cat", path));
frame.setVisible(true);
}

public static JFrame createFrame(Animal animal) {
JFrame fr = new JFrame("Stay Alive!");
fr.setResizable(false);
fr.add(new JLabel(animal.getImg()));
fr.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
fr.setSize(400, 500);
return fr;
}`


The method
animal.getImg()
returns a new
ImageIcon(imgSrc)
. But for some reason the picture isn't being added.

Answer

the right way to add an image to your Icon by setting JLabel is on this form

ImageIcon icon = new ImageIcon(animal.getImg());
JLabel thumb = new JLabel();
thumb.setIcon(icon);
Comments