ImageIcon(String)
"Creates an ImageIcon from the specified file". The actual physical image is loaded in a background thread, so even though the call might return immediately, the actually loading could still be running in the background.
This means that ImageIcon
does not throw any errors if the image can't be loaded, making sometimes annoying to work with. I prefer to use ImageIO.read
where possible, as it will throw an IOException
when it can't read a image for some reason.
The reason you image is not loading is because the image doesn't actually exist from the context of the JVM, which is looking in the current working directory of the image.
When you included resources within the context of the program, they can no longer be addressed as files and need to be loaded through the use of Class#getResource
or Class#getResourceAsStream
, depending on your needs.
For example
imageLabel = new JLabel(getClass().getResource("/staffdirectory/staff-directory.jpg"));
Where possible, you should supply the path to the image from the context of the source root
Can you give an example how I can use the "ImageIO.read" in my code?
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class staffGUI extends JFrame {
private JLabel imageLabel;
private JPanel bxPanel = new JPanel();
public staffGUI() {
super("Staff Management");
imageLabel = new JLabel();
try {
BufferedImage img = ImageIO.read(getClass().getResource("/staffdirectory/staff-directory.jpg"));
imageLabel.setIcon(new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
bxPanel.setLayout(new GridLayout(1, 1));
bxPanel.add(imageLabel);
this.setLayout(new GridLayout(1, 1));
this.add(bxPanel);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.pack();
}
}