java - My program keeps generating four times? -
for reason when run program instead of outputting 1 card choice 3, four.
i'm trying pick name array list include in path, output image, can see result system out.
heres code:
public class main { public static void main (string[] args) { main.createscreen(); } public static void createscreen() { jframe p = new jframe("angora realms"); p.setdefaultcloseoperation(jframe.exit_on_close); gamegui g = new gamegui(); p.add(g); p.setlocationrelativeto(null); p.pack(); p.setvisible(true); } }
here's create gui , paint:
@suppresswarnings("serial") public class gamegui extends jpanel implements actionlistener { public button drawcard = new button("draw card"); public gamegui() { drawcard.addactionlistener(this); add(drawcard); } @override public void actionperformed(actionevent event) { object cause = event.getsource(); if (cause == drawcard) { system.out.println("ay"); repaint(); } } @override public void paintcomponent(graphics g) { super.paintcomponent(g); cards c = new cards(); g.drawimage(c.getimage(), 0, 0, 450, 700, this); } }
and here choose card load:
public class cards { static random random = new random(); public static string getcard() { string card = null; string[] possiblecards = new string[] {"cheetah", "lion"}; card = possiblecards[random.nextint(2)]; system.out.println(card); return card; } public image getimage() { image img = null; try { img = imageio.read(getclass().getresource("/dev/angora/images/plains/" + cards.getcard() + ".png")); } catch (ioexception e) { e.printstacktrace(); } return img; } }
when run code 4 system print outs of random variation of cheetah , lion. i've been told before i'm creating 3 instances of code somewhere, have no idea where...
you don't entirely decide how , when paintcomponent()
gets executed, , doesn't matter, because method supposed paint component. gets called when repaint()
, gets called when swing thinks ui needs updated (which can when window changes focus, gets resized or bunch of other reasons).
however, you've given responsibility shouldn't have—to instantiate cards
.
move cards c = new cards();
paintcomponent()
actionperformed(actionevent event)
belongs , should fine.
Comments
Post a Comment