Re: Create JButtons from array
You are instantiating one set of buttons when you create the array, and
overwriting them with another set in the loop. The, you test for the
wrong button in the callback.
Arthur
Brian wrote:
Hi all
I'm writing a small program with a lot of buttons. To make it a little
easier to write the code I've tried to create the JButtons from an
array.
I don't work.
I don't get response from the ActionListener
Any ideas?
/Brian
Simple example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
public class ButtonPanel extends JPanel {
private Controller controller = new Controller();
private JButton btnOne, btnTwo, btnThree, btnABC, btnFour, btnFive,
btnSix, btnExtra1, btnSeven, btnEight, btnNine, btnExtra2, btnAsterix,
btnZero, btnHash, btnSearch;
private JButton[] buttons = { btnOne, btnTwo, btnThree, btnABC,
btnFour, btnFive, btnSix, btnExtra1, btnSeven, btnEight,
btnNine, btnExtra2, btnAsterix, btnZero, btnHash, btnSearch };
private String[] buttonTxt = { "1", "2", "3", "ABC", "4", "5", "6",
"Extra1", "7", "8", "9", "Extra2", "*", "0", "#", "SHg" };
public ButtonPanel() {
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton(buttonTxt[i]);
buttons[i].setSize(80, 80);
buttons[i].addActionListener(controller);
this.add(buttons[i]);
}
}
private class Controller implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnOne) {
System.out.println("test OK");
}
}
}