Button click event

2

Add some 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, I'll give a very simple example. We assume that I have a vector of 10 positions, with numbers from 1 to 10. That is, I have a position in the vector for each button inserted. Clicking on the precise button displays the vector position number for the clicked button.

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

How can I do this in the click event of the button?

    
asked by anonymous 17.03.2016 / 21:02

2 answers

2

Keep everything in the loop and declare final to 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);
}
    
17.03.2016 / 21:13
2

Use the setActionCommand() to define an action for the button. Then you can get 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 this value as int , you can use the Integer#parseInt .

    
17.03.2016 / 22:29