JButton how to get the Button Text inside event

1

Hello, I need to create n JButtons, the creation criteria is a table in the database that has n items. I have to create a button for each item and when I click the button it has to show me a message of the number of that item. Creating the button was easy, but I do not know how to create those methods.

    int qtd=cartela.qtdCartelas();
                    JToggleButton btn[] = new JToggleButton[qtd];


                    for(int i=0;i<qtd;i++)
                    {
                        numeroBotao.next();
                        btn[i]=new JToggleButton(numeroBotao.getString(1));
                        panel.add(btn[i]);
                        System.out.println();

                    }


Ao clicar no botão necessito gerar um evento.

Conseguir fazer isso:



for(int   i=0;i<qtd;i++)
                {
                    //Cria os actionListener dos botões. 
                    btn[i].addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {

                        //Necessito pegar o Texto do botão ou a posição dele no vetor
                        int l = Integer.parseInt(btn[i].getText()); 

                        //

                    }
                    });
                }
    
asked by anonymous 11.06.2016 / 20:37

1 answer

1

Why do you do 2 fors? could not add the ActionListeners in the same for the popular vector? That way you would not even need that vector. In addition, in this code:

int l = Integer.parseInt(btn[i].getText()); 

As you already have as parameter ActionEvent, you can simply use:

int l = Integer.parseInt(e.getSource().getText());

In case of error, cast to JToggleButton:

int l = Integer.parseInt((JToggleButton)(e.getSource()).getText());

Edit:

Complete code (more or less)

 int qtd = cartela.qtdCartelas();

 for (int i = 0; i < qtd; i++) {
  numeroBotao.next();
  JToggleButton botao = new JToggleButton(numeroBotao.getString(1));
  botao.addActionListener(new ActionListener() {

   public void actionPerformed(ActionEvent e) {

    //Necessito pegar o Texto do botão ou a posição dele no vetor
    int l = Integer.parseInt((JToggleButton)(e.getSource()).getText());

    //

   }
  });
  panel.add(botao);
  System.out.println();

 }
    
16.06.2016 / 00:13