How to implement actionlistener for a grid of buttons in java swing? -
i developing whack-a-mole game in java. creating 10*10 grid of buttons. not being able access id of clicked button in actionlistener. here code have far.
string buttonid; buttonpanel.setlayout(new gridlayout(10,10)); (int = 0; < 10; i++) { (int j = 0; j < 10; j++) { buttonid = integer.tostring(++buttoncount); buttons[i][j] = new jbutton(); buttons[i][j].setname(buttonid); buttons[i][j].addactionlistener(this); buttons[i][j].setdisabledicon(null); buttonpanel.add(buttons[i][j]); } } public void actionperformed(actionevent ae) { if (ae.getsource()==startbutton) { system.out.println("game has been started"); } if (ae.getsource() == "34") { //please see description below system.out.println("yes have clicked button"); } else { system.out.println("other button clicked"); } }
currently have printed few things. don't know how compare ae.getsource() button clicked. tried trying compare "34". when click 34th button on grid still prints "other button clicked".
use buttons actioncommand
property uniquely identify each button per requirements...
for (int = 0; < 10; i++) { (int j = 0; j < 10; j++) { buttonid = integer.tostring(++buttoncount); //... buttons[i][j].setactioncommand(string.tostring(buttonid)); //... } }
then in actionperformed
method, simple actioncommand
property of actionevent
....
public void actionperformed(actionevent ae) { string cmd = ae.getactioncommand(); if ("0".equals(cmd)) { //... } else if ...
equally, using buttons
array find button based on actionevent
's source
public void actionperformed(actionevent ae) { object source = ae.getsource(); (int = 0; < 10; i++) { (int j = 0; j < 10; j++) { if (source == (buttons[i][j])) { //... break; } } }
but that's you...
Comments
Post a Comment