Jbutton how to get the Text from the Button inside event

Asked

Viewed 393 times

1

Hello I need to create n Jbuttons, the creation criterion 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 don’t know how to create these 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()); 

                        //

                    }
                    });
                }
  • Does actionPerformed at the end of the code not work? What’s wrong with it? Remembering that you are using Jtogglebutton, they are a little different from the Jbuttons

1 answer

1


Why do you make 2 Fors? couldn’t add the Actionlisteners in the same for popular vector? So you wouldn’t even need that vector. Besides, in that code:

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

as you already have Actionevent as a parameter, you can simply use:

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

and in case of error, caste 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();

 }
  • Can you add how the loop would look with the suggested changes? The answer is good, just need to be complete :)

Browser other questions tagged

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