F. Aydemir
F. Aydemir

Reputation: 2735

javax.imageio.ImageIO - Cannot load the icon to JFrame

In the following code snippet I am trying to set the icon of my JFrame instance using javax.imageio.ImageIO and I get below exceptions. Could you please tell me what I am missing?

    import javax.imageio.ImageIO;
    ......
    BufferedImage image = null;
    try {
    //EXCEPTION IS thrown in the following line
        image = ImageIO.read(this.getClass().getResource("resources/Smartbook_icon.ico")); 
    } catch (IOException e) {
       ......
    }
    this.setIconImage(image);

EXCEPTION STACK TRACE

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:  input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1362)
at se.websiter.bookingapp.UI.MainFrame.setGUIIcon(MainFrame.java:4131)
at se.websiter.bookingapp.UI.MainFrame.<init>(MainFrame.java:59)
at se.websiter.bookingapp.UI.MainFrame$60.run(MainFrame.java:4167)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Upvotes: 1

Views: 1409

Answers (3)

aleroot
aleroot

Reputation: 72646

Make sure that your image is in the resource folder and use a png instead of ico, then you can load it into an ImageIcon and assign it to the JFrame :

frame.setIconImage(new ImageIcon(MainWindow.class.getResource("/resources/someicon.png")).getImage());  

Upvotes: 1

ezze
ezze

Reputation: 4110

Probably, a path to the resource is incorrect. I always use the following code snippet to set JFrame's icon image assuming resources is the subdirectory of class' package:

import java.net.URL;

// Setting window's icon
String resourcePathToIcon = String.format("/%s/resources/myicon.png",
        MyClass.class.getPackage().getName().replace('.', '/'));
URL windowIconURL = MyClass.class.getResource(resourcePathToIcon);
if (windowIconURL != null)
    setIconImage(new ImageIcon(windowIconURL).getImage());

Note that path to resource image starts with /.

Upvotes: 2

Luciano
Luciano

Reputation: 8582

The resource is not being found. Check it is copied in the compiled classes folder or inside the jar.

Upvotes: 1

Related Questions