java - Event Listeners on Dynamic Buttons -


i've been struggling while, i'm trying build program makes use of mvc pattern, dynamically creates grid of buttons (nxn) based on user input. can't right attach listeners them.

edit: meant wanted handle event inside of controller class conform mvc pattern

view

public class aigameview extends javax.swing.jframe {  private aigamemodel model; private jbutton[][] btn_arr;  public aigameview(aigamemodel m) {     model = m;     initcomponents(); }  @suppresswarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="generated code">                           private void initcomponents() {...}                                   private void startbtnactionperformed(java.awt.event.actionevent evt) {                                              options.setvisible(false);     int size = integer.parseint(size_field.gettext());     model.setsize(size);     btn_arr = new jbutton[size][size];     gamegui.setlayout(new java.awt.gridlayout(size, size));     for(int y = 0; y < size; y++)  {         for(int x = 0; x < size; x++)  {             btn_arr[y][x] = new jbutton();             btn_arr[y][x].setbackground(color.white);             gamegui.add(btn_arr[y][x]);             btn_arr[y][x].setvisible(true);          }     }     gamegui.setvisible(true);     gamegui.revalidate();     gamegui.repaint(); }         

controller

public class aigamecontroller {  private aigameview view; private aigamemodel model; private jbutton[][] buttons;  public aigamecontroller(aigamemodel m, aigameview v)    {     view = v;     model = m; } 

i've tried several things, nothing seems work , end null pointer exception. advice on ?

from code posted far, seems add call

btn_arr[y][x] = new jbutton(); btn_arr[y][x].addactionlistener(createactionlistener(y, x)); ... 

with method like

private actionlistener createactionlistener(final int y, final int x) {     return new actionlistener()     {         @override          public void actionperformed(actionevent e)         {             system.out.println("clicked "+y+" "+x);              // method should called in              // response button click:             clickedbutton(y,x);         }     }; }  private void clickedbutton(int y, int x) {     // whatever has done now... } 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -