1

I have a group of JRadioButtons. I want to use image instead of text in my JRadioButtons. So I believe i will have to use this:

JRadioButton(Icon icon, boolean selected)

Now the issue is that I am not sure about how to create this icon. I have the image that I want to use and I have copied the image in my source code folder. It is in .tiff format. i want to read that .tiff image (inputStream I believe) and convert that to icon so that i can have my JRadioButtons.

Please help in implementing this.

Thanks in advance.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sahil Chaudhary
  • 493
  • 2
  • 10
  • 29

2 Answers2

1

Assuming you put the image in your source folder, in the package com.foo.bar, and that your build process copies this file with your classes so that it's in the classpath when running the application (that's what all IDEs do by default), you can just use

new ImageIcon(MyClass.class.getResource("/com/foo/bar/MyImage.png"))

to get you an icon.

I'm not sure that Java has native support for the tiff format, so you might have to convert the image to another supported format to load it (gif, JPEG and PNG will work fine).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • instead of /com/foo/bar/MyImage.png i put the directory of a jpeg (not tiff) in my src folder. It did not work when i run it. Also i don't understand that how i am gonna read my image when i put my java applet on a server, the location is gonna change right. – Sahil Chaudhary Dec 29 '12 at 18:48
  • the program is throwing java.lang.NullPointerException, what does that mean? – Sahil Chaudhary Dec 29 '12 at 18:55
  • If it's at the root, the path would then be `/MyImage.jpg`. And no, it won't change in an applet. As long as the image is in the classpath, it will be loaded that way. I can't say what the NPE means without seeing the code causing it, and its stack trace. – JB Nizet Dec 29 '12 at 20:34
  • it works, i was making a mistake. but now when i am using the this constructor: JRadioButton(Icon icon, boolean selected) but it is not replacing the text but the button itself, idk if you understand what i am saying – Sahil Chaudhary Dec 29 '12 at 20:40
1

If you're getting a NullPointerException, it probably means that the image is not at the path you're indicating.

You said you stuck it right into the src folder so this should work:

new ImageIcon(getClass().getResource("icon.jpg"))
aly
  • 523
  • 2
  • 7