java - Last image on JLabel is shown for all after adding JLayeredPane in loop -


sorry bad title, not think of better.

i building card game.

the below method takes card object argument , returns me jlayeredpane jlabel having image card.

private jlayeredpane getcardpane(card card) {     jlayeredpane cardpane = new jlayeredpane();      gridbaglayout gblcardpane = new gridbaglayout();     cardpane.setlayout(gblcardpane);      cardimageicon = card.getimageicon();      jlabel lblcard = new jlabel() {         @override         public void paintcomponent(graphics g) {             g.drawimage(cardimageicon.getimage(), 0, 0, null);             super.paintcomponent(g);         }     };      gridbagconstraints gbclblcard = new gridbagconstraints();     cardpane.add(lblcard,gbclblcard);      return cardpane; } 

i have section below adding cards in hand jlayeredpane jlpmycards:

for (int = 0; < hand.getcardcount(); i++) {     jlayeredpane thiscard = getcardpane(hand.getcard(i));      //joptionpane.showmessagedialog(null,thiscard);      jlpmycards.add(thiscard); } 

and add jlpmycards frame.

on rendered frame see cards in hand (as per count) cards displaying last image loaded. - why?

i tried printing cards with

joptionpane.showmessagedialog(null,thiscard); 

the popup dialog showing correct images.

note: guess below method card class might create issue.

public imageicon getimageicon() {     bufferedimage img = null;     try {         img = imageio.read(new file(this.getclass().getresource(                     getvalueasstring().tolowercase() + "_of_"+                      getsuitasstring().tolowercase() + ".png").touri()));         //rescaling image         image dimg = img.getscaledinstance(100, 146, image.scale_smooth);         return new imageicon(dimg);     } catch (ioexception e) {         e.printstacktrace();     } catch (urisyntaxexception e) {         e.printstacktrace();     }     return null; } 

in each iteration of loop assign value field cardimageicon. , when rendering labels calls getimage() (in paintcomponent method) on same cardimageicon object (which set during last iteration).

instead of keeping field, can keep local variable:

final imageicom cardimageicon = card.getimageicon();  jlabel lblcard = new jlabel() {     @override     public void paintcomponent(graphics g) {         g.drawimage(cardimageicon.getimage(), 0, 0, null);         super.paintcomponent(g);     } }; 

it important declare final use in paintcomponent method.

or

perhaps can use jlabel constructor takes icon argument in constructor:

jlabel lblcard = new jlabel(card.getimageicon()); 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -