java - Adding ActionListeners to array of buttons -


i'm trying write first swing app, simple chess engine in java. i've made grid of jbuttons represent squares. looks ok, i've come across problem when trying add actionlisteners each square. want squares co-ordinates , print console when clicked. tried(i guess don't understand how actionlisteners work):

// chessboardsquares[][] 8x8 array of jbuttons  (int = 0; < 8; i++) {         (int j = 0; j < 8; j++) {              chessboardsquares[i][j].addactionlistener(new actionlistener(){                  @override                 public void actionperformed(actionevent e) {                      system.out.println("x: "+i+"y: "+j);                  }              });         }     } 

you need use either fields or final local variables inside anonymous inner class.

for (int = 0; < 8; i++) {     (int j = 0; j < 8; j++) {         final int finali = i;         final int finalj = j;          chessboardsquares[i][j].addactionlistener(new actionlistener(){              @override             public void actionperformed(actionevent e) {                 system.out.println("x: " + finali +"y: " + finalj);             }         });     } } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -