I am trying to get a image as the icon for a JFrame window, but I got this error while loading the image.
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at quest2.WindowFrame.<init>(WindowFrame.java:21)
at quest2.WindowFrame.main(WindowFrame.java:39)
This is the code, but I cut out a few lines that do not pertain to this question.
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class WindowFrame extends JFrame{
private static BufferedImage BufImage;
Image image; //The image for the icon of the frame
private static final long serialVersionUID = 1L;
public WindowFrame() {
//Get a Image for the Icon
try {
BufImage = ImageIO.read(getClass().getResource("/src/quest2/Logo.png"));
} catch (IOException e) {
e.printStackTrace();
}
ImageIcon ii = new ImageIcon(BufImage);
image = ii.getImage();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(720, 480);
setTitle("Quest 2");
setVisible(true);
setResizable(false);
setIconImage(image);
setLocationRelativeTo(null);
}
public static void main(String args[]) {
new WindowFrame();
}
}
I'm not sure what I'm doing wrong, so if anyone could give me help with this, that would be great.
src
won't exist at run time...
You should be using...
getClass().getResource("/quest2/Logo.png")
instead
Updated
You should also be catering for the situation where the image may be null
, for example...
try {
BufImage = ImageIO.read(getClass().getResource("/quest2/Logo.png"));
} catch (IOException e) {
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(720, 480);
setTitle("Quest 2");
if (BufImage != null) {
ImageIcon ii = new ImageIcon(BufImage);
image = ii.getImage();
setIconImage(image);
}
setLocationRelativeTo(null);
setVisible(true);
Also, changing the resizable
state of the frame will affect it's size, you should do this before setting the frames size (preferably using pack
) and call setVisible
last
You may also want to take a look at Initial Threads and ensure that the UI is initialised within the context of the Event Dispatcing Thread