Page 1 of 2 12 LastLast
Results 1 to 20 of 29
  1. #1
    Astralogic is offline Member
    Join Date
    Mar 2012
    Posts
    71
    Rep Power
    0

    Default Runtime error when trying to display an ImageIcon.

    I seem to be running into problems at every turn lately :/

    This is the program:

    Java Code:
    import java.awt.FlowLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class ImageTutorial extends JFrame {
    	
    	private ImageIcon image1;
    	private JLabel label1;
    	private ImageIcon image2;
    	private JLabel label2;
    	
    	ImageTutorial() {
    		setLayout(new FlowLayout());
    		
    		image1 = new ImageIcon(getClass().getResource("Skull.jpg)"));
    		label1 = new JLabel(image1);
    		add(label1);
    		
    		image2 = new ImageIcon(getClass().getResource("human_mage.jpg)"));
    		label2 = new JLabel(image2);
    		add(label2);
    	}
    	
    	public static void main(String[] args) {
    		ImageTutorial gui = new ImageTutorial();
    		gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		gui.setTitle("Images");
    		gui.pack();
    		gui.setVisible(true);
    		
    	}
    
    }
    This is the runtime error I get, which I don't understand:

    Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
    at ImageTutorial.<init>(ImageTutorial.java:16)
    at ImageTutorial.main(ImageTutorial.java:26)
    Does anyone have any idea what's wrong here?

    Thanks
    Astralogic

  2. #2
    kris5228 is offline Member
    Join Date
    Nov 2011
    Posts
    17
    Rep Power
    0

    Default Re: Runtime error when trying to display an ImageIcon.

    Hi,

    You need to replace this:

    Java Code:
    image1 = new ImageIcon(getClass().getResource("Skull.jpg)"));
            label1 = new JLabel(image1);
            add(label1);
             
            image2 = new ImageIcon(getClass().getResource("human_mage.jpg)"));
            label2 = new JLabel(image2);
            add(label2);
    with this:

    Java Code:
    image1 = new ImageIcon("DIR\\Skull.jpg");
            label1 = new JLabel(image1);
            add(label1);
             
            image2 = new ImageIcon("DIR\\human_mage.jpg");
            label2 = new JLabel(image2);
            add(label2);
    That should work for you :)

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,242
    Rep Power
    19

    Default Re: Runtime error when trying to display an ImageIcon.

    Your resource isn't where the program is looking for it.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    Astralogic is offline Member
    Join Date
    Mar 2012
    Posts
    71
    Rep Power
    0

    Default Re: Runtime error when trying to display an ImageIcon.

    Where does the program look if there is no path? I added the images to my project and put the files in my project folder in the bin folder (eclipse did that when I dragged the images onto the package in the package explorer). I added "bin\\" and it didn't works so I tried "\\bin\\" and that didn't work. So then I copied the images out of the bin folder up one level into the root of the project folder and removed the file path again to retry it. Still didn't work.

    If an image is loaded by using its full path, will that file always have to be in that place when the program is run after it is compiled? Or will the image become part of the jar file and always be available to the compiled program?

    Here's the new code:

    Java Code:
    image1 = new ImageIcon(getClass().getResource("C:\\Users\\Calvin\\workspace\\ImageTutorial\\bin\\Skull.jpg)"));
    label1 = new JLabel(image1);
    add(label1);
    		
    image2 = new ImageIcon(getClass().getResource("C:\\Users\\Calvin\\workspace\\ImageTutorial\\bin\\human_mage.jpg)"));
    label2 = new JLabel(image2);
    add(label2);
    I get exactly the same runtime error:

    Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
    at ImageTutorial.<init>(ImageTutorial.java:16)
    at ImageTutorial.main(ImageTutorial.java:26)

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,242
    Rep Power
    19

    Default Re: Runtime error when trying to display an ImageIcon.

    Never use the Windows' backslash separator when dealing with paths in Java. A forward slash is interpreted correctly for all current versions of any OS, including Windows.

    Check out the tutorial on How to Use Icons (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components) -- in fact, get familiar with the entire tutorial as you can find most stuff quicker there than waiting for someone to answer your question on a forum.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Runtime error when trying to display an ImageIcon.

    If the images are in the root (ie the top of 'bin') then getResource will look in <packagename>/<your resource>.
    This will probably (as many things do) fail if you are using the default package (ie there is no package definition for you class).
    If you don't want it to look there (in your case you probably don't) then add a '/' to the start of the path you want and it will look in the root (which should be the bin).

    What you don't want to do is put in full system paths, as that's completely untransportable.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    Astralogic is offline Member
    Join Date
    Mar 2012
    Posts
    71
    Rep Power
    0

    Default Re: Runtime error when trying to display an ImageIcon.

    It's just not working, no matter how I write the path. From what you've both said this should work:

    Java Code:
    import java.awt.FlowLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class ImageTutorial extends JFrame {
    	
    	private ImageIcon image1;
    	private JLabel label1;
    	private ImageIcon image2;
    	private JLabel label2;
    	
    	ImageTutorial() {
    		setLayout(new FlowLayout());
    		
    		image1 = new ImageIcon(getClass().getResource("/Skull.jpg)"));
    		label1 = new JLabel(image1);
    		add(label1);
    		
    		image2 = new ImageIcon(getClass().getResource("/human_mage.jpg)"));
    		label2 = new JLabel(image2);
    		add(label2);
    	}
    	
    	public static void main(String[] args) {
    		ImageTutorial gui = new ImageTutorial();
    		gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		gui.setTitle("Images");
    		gui.pack();
    		gui.setVisible(true);
    		
    	}
    
    }
    I even tried "/bin/***.jpg" and that didn't work. I still get the same error.

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Runtime error when trying to display an ImageIcon.

    How are you executing this?
    When executing, get the URL from getResource and print it out:
    Java Code:
    URL skullURL = getClass().getResource("/Skull.jpg)");
    System.out.println(skullURL.getPath());
    then at least you'll see where it's trying to look.

    It could simply be a setup thing with your IDE.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    Astralogic is offline Member
    Join Date
    Mar 2012
    Posts
    71
    Rep Power
    0

    Default Re: Runtime error when trying to display an ImageIcon.

    Quote Originally Posted by Tolls View Post
    How are you executing this?
    When executing, get the URL from getResource and print it out:
    Java Code:
    URL skullURL = getClass().getResource("/Skull.jpg)");
    System.out.println(skullURL.getPath());
    then at least you'll see where it's trying to look.

    It could simply be a setup thing with your IDE.
    I commented out almost everything in the code and pasted that into main but it says this:

    Cannot make a static reference to the non-static method getClass() from the type Object
    the getClass() method is underlined in red. I tried to make main() non-static but that was wrong of me to attempt, it seems main() HAS to be static. So I made a non-static method for those two lines of code but obviously, static methods like main() can't call non-static methods *slaps forehead*.

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default Re: Runtime error when trying to display an ImageIcon.

    Resource paths have (almost) nothing to do with paths in a file system. A resource path is relative to the class object that refers to it; there is detailed documentation for it in the Class class API.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  11. #11
    milovan is offline Senior Member
    Join Date
    Jan 2011
    Location
    Belgrade, Serbia
    Posts
    301
    Rep Power
    4

    Default Re: Runtime error when trying to display an ImageIcon.

    And before everything put the brackets in the right place. I'm sure you don't have file with .jpg) extension...

    ().getResource("/Skull.jpg)");

  12. #12
    Astralogic is offline Member
    Join Date
    Mar 2012
    Posts
    71
    Rep Power
    0

    Default Re: Runtime error when trying to display an ImageIcon.

    Quote Originally Posted by JosAH View Post
    Resource paths have (almost) nothing to do with paths in a file system. A resource path is relative to the class object that refers to it.

    kind regards,

    Jos
    Then "/Skull.jpg" is correct as it's in the project's bin folder. But it still doesn't work.

  13. #13
    Astralogic is offline Member
    Join Date
    Mar 2012
    Posts
    71
    Rep Power
    0

    Default Re: Runtime error when trying to display an ImageIcon.

    Quote Originally Posted by milovan View Post
    And before everything put the brackets in the right place. I'm sure you don't have file with .jpg) extension...
    Well spotted, I've corrected it.

  14. #14
    milovan is offline Senior Member
    Join Date
    Jan 2011
    Location
    Belgrade, Serbia
    Posts
    301
    Rep Power
    4

    Default Re: Runtime error when trying to display an ImageIcon.

    I would suggest to always wrap the problematic part of code into try/catch block and then analyze catched exception because it could be more describing.

  15. #15
    Astralogic is offline Member
    Join Date
    Mar 2012
    Posts
    71
    Rep Power
    0

    Default Re: Runtime error when trying to display an ImageIcon.

    Quote Originally Posted by milovan View Post
    I would suggest to always wrap the problematic part of code into try/catch block and then analyze catched exception because it could be more describing.
    There's no need it was those bloody brackets

    I could kill myself sometimes.

    Astralogic

  16. #16
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Runtime error when trying to display an ImageIcon.

    Quote Originally Posted by JosAH View Post
    Resource paths have (almost) nothing to do with paths in a file system. A resource path is relative to the class object that refers to it; there is detailed documentation for it in the Class class API.

    kind regards,

    Jos
    Yes, but the getPath will inform you where exactly (including the position inside a jar) it is looking for the resource in question.
    And, of course, it would also have shown up the bracket...:)
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  17. #17
    Astralogic is offline Member
    Join Date
    Mar 2012
    Posts
    71
    Rep Power
    0

    Default Re: Runtime error when trying to display an ImageIcon.

    OK I might have made a typo in that program but I'm having the exact same problem in this one and there is no typo:

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import sun.audio.*;
     
    public class Sound {
     
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setSize(200, 200);
            JButton button = new JButton("Play");
            frame.add(button);
            button.addActionListener(new AL());
            frame.setVisible(true);
        }
         
        public static class AL implements ActionListener {
            public final void actionPerformed(ActionEvent e) {
                music();           
            }
        }
         
        public static void music() {
             
                AudioPlayer player;
                AudioStream stream;
                AudioData data;
                ContinuousAudioDataStream loop;
                player = AudioPlayer.player;
                loop = null;
         
            try {
                stream = new AudioStream(new FileInputStream("/Passage - Ludovico Einaudi.mp3"));
                data = stream.getData();
                loop = new ContinuousAudioDataStream(data);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
             
            player.start(loop);
        }
    }
    java.io.FileNotFoundException: \Passage - Ludovico Einaudi.mp3 (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.jav a:138)
    at java.io.FileInputStream.<init>(FileInputStream.jav a:97)
    at Sound.music(Sound.java:38)
    at Sound$AL.actionPerformed(Sound.java:24)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.jav a:6505)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3321)
    at java.awt.Component.processEvent(Component.java:627 0)
    at java.awt.Container.processEvent(Container.java:222 9)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4861)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2713 )
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:707)
    at java.awt.EventQueue.access$000(EventQueue.java:101 )
    at java.awt.EventQueue$3.run(EventQueue.java:666)
    at java.awt.EventQueue$3.run(EventQueue.java:664)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:680)
    at java.awt.EventQueue$4.run(EventQueue.java:678)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 677)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:128)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:117)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:113)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:105)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:90)
    Tolls' idea of using the getResource() method still seems like the only thing to try, but being a newbie to Java I don't quite know where I can put it without getting that "Cannot make a static reference to the non-static method getClass() from the type Object" error.

  18. #18
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: Runtime error when trying to display an ImageIcon.

    Do the same as I suggested above (which would have worked had you put it in the same place as you were trying to create the ImageIcon by the way), but using File.
    Java Code:
    File f = new File("/Passage - Ludovico Einaudi.mp3");
    System.out.println(f.getAbsolutePath());
    Whenever you get a FNF exception it's always worth sticking some debug like the above (if possible) to try and see where exactly the code is looking for the file in question.

    Note, though, that you are not using getResource this time. You are using the file system, which means "/" means whatever it does in the file system, which is usually the root of the file system...C:\ in windows, for example.
    In you current case I suspect
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  19. #19
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,242
    Rep Power
    19

    Default Re: Runtime error when trying to display an ImageIcon.

    Quote Originally Posted by Tolls View Post
    You are using the file system, which means "/" means whatever it does in the file system, which is usually the root of the file system...C:\ in windows, for example.
    Doesn't it mean the current working directory?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  20. #20
    Astralogic is offline Member
    Join Date
    Mar 2012
    Posts
    71
    Rep Power
    0

    Default Re: Runtime error when trying to display an ImageIcon.

    Quote Originally Posted by Tolls View Post
    Do the same as I suggested above (which would have worked had you put it in the same place as you were trying to create the ImageIcon by the way), but using File.
    Java Code:
    File f = new File("/Passage - Ludovico Einaudi.mp3");
    System.out.println(f.getAbsolutePath());
    Whenever you get a FNF exception it's always worth sticking some debug like the above (if possible) to try and see where exactly the code is looking for the file in question.

    Note, though, that you are not using getResource this time. You are using the file system, which means "/" means whatever it does in the file system, which is usually the root of the file system...C:\ in windows, for example.
    In you current case I suspect
    I tried those lines of code in both programs, in the image program it gave me "C:\human_mage.jpg" which doesn't exist. The image is in the bin folder, and since the program successfully displays the image it obviously isn't looking in the root of the drive.

    In the sound program it gives "C:\Passage - Ludovico Einaudi.mp3". Presumably it's not actually looking there, but I copied the file there and the program still gives the FNF error.




    Edit: Also I ran this:

    Java Code:
    public class Sound {
    
    	public static void main(String[] args) {
    		JFrame frame = new JFrame();
    		frame.setSize(200, 200);
    		JButton button = new JButton("Play");
    		frame.add(button);
    		button.addActionListener(new AL());
    		frame.setVisible(true);
    	}
    	
    	public static class AL implements ActionListener {
    		public final void actionPerformed(ActionEvent e) {
    			URL skullURL = getClass().getResource("/Passage - Ludovico Einaudi.mp3");
    			System.out.println(skullURL.getPath());
    //			music();			
    		}
    	}
    And it out put "/C:/Users/Calvin/workspace/Sound/bin/Passage%20-%20Ludovico%20Einaudi.mp3" so I tried removing the first / from the file name in the program and the program output the same thing so I assume that /C:/ is OK. Problem is that's exactly where the file is that it's saying it can't find.
    Last edited by Astralogic; 09-06-2012 at 11:11 PM.

Page 1 of 2 12 LastLast

Similar Threads

  1. display ImageIcon in JList when tab is changed.
    By gammaman in forum AWT / Swing
    Replies: 0
    Last Post: 05-25-2012, 03:15 PM
  2. Error in Javax.Swing.ImageIcon
    By raj.mscking@gmail.com in forum Advanced Java
    Replies: 7
    Last Post: 01-28-2012, 12:14 PM
  3. [SOLVED] JButton does not display ImageIcon properly
    By Singing Boyo in forum New To Java
    Replies: 1
    Last Post: 04-17-2009, 03:47 AM
  4. Replies: 3
    Last Post: 01-23-2009, 08:53 AM
  5. Replies: 1
    Last Post: 10-29-2008, 07:01 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •