1

Цикл перебирает компоненты JPanel, которые являются кнопками, но при этом нет возможности добавить к ним ActionListener, только ComponentListener и FocusListener

private void buttonListeners(){
    for(int i = 0; i < jPanel.getComponentCount()-4; i++){
        jPanel.getComponent(i).addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {

            }
        });
    }
}

1 ответ 1

3

getComponent() возвращает объект типа Component. Чтобы добавить к этому компоненту ActionListener, нужно приравнять его к JButton.

private void buttonListeners() {
    for(int i = 0; i < jPanel.getComponentCount() - 4; i++) {
        ((JButton)jPanel.getComponent(i)).addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {

            }
        });
    }
}

Ваш ответ

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

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.