Best way to assign an image file to a JLabel?
Exctly what the title says. Right now I have a character who's icon alternates (to provide the illusion of running for example), what I have done is I have separate JLabels for each image, with their visibility set to false, and my character changes his using using
player.setIcon(runL3.getIcon());
Seems like there must be a more efficient way of doing this so maybe someone could help me out?
Re: Best way to assign an image file to a JLabel?
This is something I am just starting to work on myself (today in fact). What code do you have so far?
Re: Best way to assign an image file to a JLabel?
Basically I have 8 images my character needs to cycle through. So what I have right now are 8 JLabels, each with their icon set to one of the images, but their visibility set to false.
Then I have a counter which cycles through the image which my main character displays, he is the code for that:
if(keys[37]){ //left arrow
lcount++;
if(lcount>=1&&lcount<=3){player.setIcon(runL1.getI con());}
if(lcount>=4&&lcount<=6){player.setIcon(runL2.getI con());}
if(lcount>=7&&lcount<=9){player.setIcon(runL1.getI con());}
if(lcount>=10&&lcount<=12){player.setIcon(runL3.ge tIcon());}
if(lcount==13){lcount = 0;}
I have the same thing going on the right side with a variable name rcount.
Re: Best way to assign an image file to a JLabel?
What does your getIcon(...) method do? If it reads in an image from a file or resource, then this is inefficient, and you'll be better served reading in the image once and storing it in a variable or collection.
Re: Best way to assign an image file to a JLabel?
It's not a method I created. It is part of the JLabel class, basically an easy way to give an object an image I guess. Can you elaborate on the "storing the image in a variable" part?
Re: Best way to assign an image file to a JLabel?
Fubarable wasn't questioning the setIcon( ... ) method but your getIcon( ... ) method is suspicious ...
kind regards,
Jos