Re: Create JButtons from array
On 2008-02-02 18:50 +0100, Brian allegedly 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"); } } }
The moment your "buttons" array is created (at instantiation time),
btnOne et al. haven't been set to a specific object. Consequently,
they're holding the value null. What's put in your array isn't the
variable btnOne*, but the value they're holding -- in this case: null.
Later on, when you fill the array, the values they were holding get
replaced. btnOne etc. are not affected by this and are null throughout
your program. Consequently your equality comparision in
actionPerformed(ActionEvent) fails.
* You'd need variable pointers for that. There are no valiable pointers
in Java.
Learn more about variables and Objects:
<> err... Could somebody provide me with a good link on this topic? I
remember a nice one with a remote in a glass, but can't seem to find it.
You could simply replace:
e.getSource() == btnOne
with:
e.getSource() == buttons[0]
or use a java.util.List instead of an array and use (not with an "if"):
buttons.indexOf(e.getSource())
DF.