java - Change JButton ImageIcon on Click -



java - Change JButton ImageIcon on Click -

i attempting create jframe application in java similar minesweeper different rules/goals.

i have created grid of jbuttons, 12x12 , have jbutton 2d array.

i'm trying alter image of button when clicked (make x or image of gold nugget). know how if had individual name each button, seems not logical create 144 individual buttons , name each of them.

so need on click event of button, change/set image of button, in action listener can figure out if know specific array coordinates of button.

my question how alter image of specific button? or how values of button[?][?] can alter image of button?

thanks!

public class goldpanel extends jpanel{ imageicon ximage = new imageicon("x.png"); imageicon goldimage = new imageicon(""); losingbuttonlistener losebutton = new losingbuttonlistener(); winningbuttonlistener winbutton = new winningbuttonlistener(); jbutton[][] button = new jbutton[12][12]; //creates layout gridlayout layout = new gridlayout(12,12); random myrand = new random(); public goldpanel(){ //creates panel name/title/score/etc jpanel titlepanel = new jpanel(); add(titlepanel); jlabel title = new jlabel("welcome goldmine game!"); titlepanel.add(title); //creates panel game board jpanel gamepanel = new jpanel(); add(gamepanel); gamepanel.setlayout(layout); for(int i=0;i<12;i++) { for(int j=0;j<12;j++) { button[i][j] = new jbutton(" "); gamepanel.add(button[i][j]); button[i][j].addactionlistener(losebutton); } } button[0][0].addactionlistener(winbutton); }//end constuctor private class losingbuttonlistener implements actionlistener { @override public void actionperformed(actionevent e) { // todo auto-generated method stub }//actionperformed }//buttonlistener private class winningbuttonlistener implements actionlistener { @override public void actionperformed(actionevent e) { // todo auto-generated method stub system.out.println("you win"); }//actionperformed }//winningbuttonlistener }//end goldpanel class

if @ actionevent documentation page see every action event constructed object source. means if scheme registers click on button button gets passed constructor of actionevent source.

so you're getting right button casting object right class.

class="lang-java prettyprint-override">[...] public void actionperformed(actionevent ae) { jbutton therightbutton = (jbutton) ae.getsource(); // stuff button... } [...]

java arrays eclipse jbutton imageicon

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -