Simple ActionListener within a 2D array of JButtons

后端 未结 4 1422
不思量自难忘°
不思量自难忘° 2020-12-04 00:56

Okay so I am making a 2d array of JToggleButtons. I got the action listener up and going, but I have no way to tell which button is which.

If I click one, all it ret

4条回答
  •  遥遥无期
    2020-12-04 01:38

    Just add the row and column data to each listener. You could add an explicit constructor, but I suggest adding a little method (which may have more added to it later).

                buttons[i][j].addActionListener(e(i, j));
    ...
    private ActionListener e(final int i, final int j) {
        return new ActionListener() {
            // i and j available here
            ...
    

    (In JDK8 you should be able to use a lambda to reduce the syntax clutter.)

    And then renaming it with a better name.

提交回复
热议问题