Event click button

Asked

Viewed 1,031 times

2

I add a few buttons like this:

JButton bt;
for(int i = 0; i <= 10; i++){
    bt = new JButton("BT : " + i);
    bt.setPreferredSize(new Dimension(80, 80));
    bt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // fazer algo
        }
    });

    jPanel.add(bt);
}

I need an action for each button, let me give you a very simple example. Let’s assume that I have a 10 position vector, with numbers from 1 to 10. That is, I have a position in the vector for each button inserted. When clicking on the right button display the vector position number for the clicked button.

Button 1 - displays vector position 1 Boot 2 - displays vector position 2 Boot 3 - displays position 3 of vector .... and so on

How can I do this in the boot click event?

2 answers

2

Keep everything in the loop and declare a final with what you want to write/manipulate.

for(int i = 0; i <= 10; i++){
    JButton bt = new JButton("BT : " + i);
    final Integer valor = Integer.valueOf(i);
    bt.setPreferredSize(new Dimension(80, 80));
    bt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Valor : " + valor);
        }
    });
    jPanel.add(bt);
}
  • 1

    Why the Integer>valueOf if the int to integer cast is automatic? See ideone

  • Just for clarity @Diegof. Anyway it was worth.

2

Use the method setActionCommand() to set an action for the button. Then you can take this value when the event is triggered:

for(int i = 0; i <= 10; i++){
    bt = new JButton("BT : " + i);
    bt.setActionCommand(String.valueOf(i));
    bt.setPreferredSize(new Dimension(80, 80));
    bt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Índice: " + e.getActionCommand());
        }
    });
    jPanel.add(bt);
}

If you need that amount as int, can use the method Integer#parseInt.

  • I didn’t know that command, interesting. I am not the OP, but it would be interesting an example of the use of this to generate within the for, as it suggests in the question.

Browser other questions tagged

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