The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Re: How to display a button with an image on it?

Originally Posted by relixus

try this:

Icon icon = new ImageIcon(getClass().getResource("Poppy.jpg"));

Hi relixus

Thank you very much for your advice, I tried to replace "Icon icon = new ImageIcon("Poppy.jpg")" with yours "Icon icon = new ImageIcon(getClass().getResource("Poppy.jpg"))", then ran it again, now it is not even showing the frame with the blank button?
Any more thought?

Re: How to display a button with an image on it?

Originally Posted by javapenguin

Do you have to do getClass().getResource(Image title)?

Why not just...

ImageIcon icon = new ImageIcon("Poppy.jpg");

Try packaging your application and running it on a different computer. Using getResource allows you to package the app and images into a single jar. Relying on full paths is not very portable from one computer to the next, and in many cases will break immediately.

Re: How to display a button with an image on it?

Originally Posted by copeg

Try packaging your application and running it on a different computer. Using getResource allows you to package the app and images into a single jar. Relying on full paths is not very portable from one computer to the next, and in many cases will break immediately.

So how would I get it to work on both my computer and another computer? Would I have to import a jar file?

Re: How to display a button with an image on it?

when you compile your project into a jar file the image for your button will be included inside the jar file, and you will have problems referencing to it directly, u have to use getClass().getResource() to use those resources inside your jar file.

Re: How to display a button with an image on it?

Originally Posted by ice

Hi relixus

Thank you very much for your advice, I tried to replace "Icon icon = new ImageIcon("Poppy.jpg")" with yours "Icon icon = new ImageIcon(getClass().getResource("Poppy.jpg"))", then ran it again, now it is not even showing the frame with the blank button?
Any more thought?

is poppy.jpg in the same directory as your java file? u should put them in the same folder.