Josh Mo
Josh Mo

Reputation: 137

How to show image in JOptionPane in Netbeans

The code I used in JGrasp to show the image is not working in Netbeans

The code I used in JGrasp is

final ImageIcon icon1 = new ImageIcon("image/money.gif");
JOptionPane.showMessageDialog(null, " blah blah", "Text",
   JOptionPane.INFORMATION_MESSAGE,   icon1);

If I wanted to show an image in JOptionPane.showInputDialog, would it be the same for JOptionPane.showMessageDialog?

Any help is greatly appreciated!

Edit: I don't think that the location is the problem because when I do this

menuPic = new javax.swing.JButton();
menuPic.setIcon(new javax.swing.ImageIcon(
    getClass().getResource("image/money.gif")));

It shows the image fine, but when I try to add an image to my JOptionPane, it doesn't show anything.

Upvotes: 1

Views: 8369

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

This is the same exact issue as in your previous question, but now in reverse. The key is where are the image files located. And the key to this is that you are now getting the image as a File while previously you were getting it as a Resource, and Java looks in two different places for these.

Now the files must be in an image subdirectory off of the user directory. You can get the user directory by calling

System.out.println(System.getProperty("user.dir"));

Once you get the user directory, add an "/image/money.gif" to it, and that's the path to your image File (again, not a resource as you did in the previous example).

Edit
Regarding your comment:

I don't think that the location is the problem because when i do this

menuPic = new javax.swing.JButton(); menuPic.setIcon(new javax.swing.ImageIcon(getClass().getResource("image/money.gif")));

It shows the image fine, but when i try to add an image to my joptionpane it doesn't show anything

Of course -- that's what I'm trying to say all long. In this second instance you're getting the image as a resource, not a file, and that makes a huge difference for where Java looks for the jpg file.

If for your JOptionPane you looked for the image as a resource, it will work fine since you know where the jpg resource is located. i.e., this will likely work:

// final ImageIcon icon1 = new ImageIcon("image/money.gif");
final ImageIcon icon1 = new javax.swing.ImageIcon(getClass().getResource("image/money.gif"))
JOptionPane.showMessageDialog(null, " blah blah", "Text",
   JOptionPane.INFORMATION_MESSAGE,   icon1);

But still if you want to find your image as a File -- and sometimes this is necessary, first you must find the user.dir as I've suggested above.

Upvotes: 4

Related Questions