How to generate multiple buttons with the same variable and catch them separately

Asked

Viewed 51 times

0

Hello, I’ll put the important part of the code here and then I’ll explain what I want to do.

Main:

public static JButton sala;
public static int contagemTurmas = 0;

botaoSalvar.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {   
            gerarTableTurma(turmaName.getText(), contagemTurmas, panelCriados);
        }
    });

sala.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            System.out.println(sala.getText());
            turmaName.setText(sala.getText());
        }
    });

Part generating the various buttons from the vairavel sala

public static void gerarTableTurma(String turma, int posicao, JPanel panel) 
{   
    sala = new JButton(turma); //turma = JTextArea
    sala.setFont(new Font("Tahoma", Font.PLAIN, 30));
    sala.setBounds(10, 11 + (contagemTurmas * 43), 792, 32);
    panel.add(sala);

    contagemTurmas ++;

    panel.repaint();
}

I would like to take the event from a button, however do not know the button, so I created several buttons in the same variable, so no matter what button clicked, I would know which would be just testing the variable sala, how can I do that ?? since when I click on one of the buttons nothing happens at all

  • I honestly didn’t understand anything you explained.

  • @Diegof I basically want to create several buttons, but I don’t want to have to create a variable for each of them, I want to be able to change them and know if any of them were clicked from just one variable

  • I believe that this answer solve your problem perfectly :)

  • @Diegof solved perfectly, thank you.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.