java - Finding the source of an ActionEvent in a JButton[][] array without using nested loops? -


i've created jframe application 8x8 array of jbuttons[][] corresponding array of selected & deselected imageicons. when button pressed, selects button using setselection() , deselects other buttons. however, if button adjacent selected button pressed, selected button , adjacent button swap imageicons.

i've managed of this, using nested loops within actionevent determine adjacent buttons, selected button, , deselected buttons simultaneously becomes logical nightmare.

public void actionperformed(actionevent event) { (int row = 0; row < 8; row++) {   (int col = 0; col < 8; col++) {     if (event.getsource() == buttons[row][col]) {       if (row<7) buttonsadjacent[row+1][col] = true;       if (row>0) buttonsadjacent[row-1][col] = true;       if (col<7) buttonsadjacent[row][col+1] = true;       if (col>0) buttonsadjacent[row][col-1] = true;       buttons[row][col].setselected(true);       }     }   } } 

how can put actionlisteners each adjacent button @ array index [row][col] determine if adjacent button has been pressed? , how can reassign actionlisteners every time new button has been selected?

as shown in complete example, can calculate index of jbutton in list<jbutton> function of row , column given grid size, e.g. n * n. see comments , edit history alternatives.

private static final int n = 5;  private jbutton getgridbutton(int r, int c) {     int index = r * n + c;     return list.get(index); } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -