java - How to get specific ID for a JButton? -


i'm trying build program utilizes 3x3 grid of buttons (using java swing), initialize gridlayout , loop create buttons:

     panel.setborder(borderfactory.createemptyborder(3,3,5,5))      panel.setlayout(new gridlayout(3,3,10,10));      string[] buttons = {"top left", "top middle", "top right", "middle left", "middle", "middle right", "bottom left", "bottom middle", "bottom right"};      for(int = 0; < buttons.length; i++) {         buttray[i] = new jbutton(buttons[i]);         panel.add(buttray[i]);         buttray[i].addactionlistener(this);     } 

the buttons load fine, not understand how use actionlisteners differentiate between buttons. when check paramstring() method printout, each button gives same modifier:

top left action_performed,cmd=top left,when=1431640106712,modifiers=button1 top middle action_performed,cmd=top middle,when=1431640107566,modifiers=button1 top right action_performed,cmd=top right,when=1431640107978,modifiers=button1 

does modifier value act button's identifier, , if so, how change it?

there multiple ways distinguish button fired actionevent:

  1. set/get action command of each button (eg if (e.getactioncommand().equals("top left"))
  2. use == compare instances (eg if (e.getsource() == buttray[0] ))
  3. get text of jbutton (eg if (e.getsource().gettext().equals("top left"))
  4. set/get name of jbutton (eg if (e.getsource().getname().equals("top left"))
  5. add different actionlistener each button (in other words 1:1 listener button)
  6. ...and perhaps more ways added in comments section below.

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -