2

Есть массив из кнопок

JButton buttons[] = new JButton[9];
for (int i = 0; i < buttons.length; i++) {
    buttons[i] = new JButton();
}

И как сделать чтобы при клике на кнопку он получал свой индекс. Например, при нажатии на кнопку 4 выводился ее индекс в массиве (3);

1 ответ 1

6
JButton buttons[] = new JButton[9];
for (int i = 0; i < buttons.length; i++) {
    buttons[i] = new JButton();
    final int finalI = i;
    buttons[i].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println(finalI);
        }
    });
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.