0

I have imported a few images in my Netbeans Java project. I want to set one of them as a label's icon when I click a button. I don't want to use the path of the image in the code.

Please help me.

Roman C
  • 49,761
  • 33
  • 66
  • 176
Shivam
  • 13
  • 4
  • what ide are you using? Netbeans? – Nitesh Verma Jan 12 '13 at 08:49
  • __(I don't want to use the path of the image in the code.)__ why so? – joey rohan Jan 12 '13 at 08:52
  • 1
    You could set the path element of the images as a static variable, that way, if it changes, you only need to change it in one place – MadProgrammer Jan 12 '13 at 09:03
  • @joey, what i want is that when i click a button, the particular image should be set as the label's icon. Suppose i use the images's path on my system and i run the project on another system, then it will fail. In simple words, i want to make the setting of image icon path independent. – Shivam Jan 12 '13 at 09:09
  • If you run in some other system, you have to paste the image in your project.See my answer. `getClass().getResource("/yourImageName.jpg")` Will do it for you.Ask for EG if you want.But its better if you can make your own efforts from here. – joey rohan Jan 12 '13 at 09:12
  • @Nitesh, yes m using nb 7.2 – Shivam Jan 12 '13 at 09:13
  • @joey, i have not 'imported' the image in my source of JFrame (i.e. using 'import' keyword), i have just added to the package of my project. will this code still work? – Shivam Jan 12 '13 at 09:16
  • Yeah! thats what! Its fine like that.It will work. – joey rohan Jan 12 '13 at 09:18
  • Try, if you can't make it out, feel free to post your code. – joey rohan Jan 12 '13 at 09:22

1 Answers1

2

If you have imported images in your project then use :

myJLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/yourImageName.jpg")));

And enclose it in the actionListener block of that button.

Refer this to know how to use Jbutton.

Roman C
  • 49,761
  • 33
  • 66
  • 176
joey rohan
  • 3,505
  • 5
  • 33
  • 70