Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Add actionlistener to JButtons in a collection

843807Nov 8 2009 — edited Nov 8 2009
I can't seem to successfully add actionlisteners to JButtons in an ArrayList.

I have a class called PanelGenericButtons that creates a JPanel with some JButtons in it. I am attempting to keep this class as "dumb" as possible, so it only deals with the panel creation and layout, and it does not include the actionListeners. As the name suggests, it is intended to create a panel with an arbitrary number of buttons that is specified by a client-defined TreeMap (*buttonInfo*), as follows
		
ArrayList<JButton> buttons = new ArrayList<JButton>();

...

for (String s:  buttonInfo.keySet()){
			JButton b = new JButton();
			b.setText(s);
			b.setName(s);
			b.setMnemonic(buttonInfo.get(s));
			buttons.add(b);
			}
The buttons ArrayList can then be accessed by...
	public ArrayList<JButton> getButtonList() {
		return buttons;
		}
The client code then assigns actionListeners to the instance (called panel in this case) as follows...
		for (JButton b: panel.getButtonList()){
			b.addActionListener(buttonActionListener());		
			}
I have tested it as follows with an actionListener that changes buttonWasClicked to true, and the tests all pass
		for (JButton b: panel.getButtonList()){
			buttonWasClicked = false;
			b.addActionListener(runButtonActionListener());
			b.doClick();
			assertTrue(buttonWasClicked);
			}
...however, it doesn't work, because when I launch the panel, clicking the buttons does not yield the action specified.

The only thing I can think of is that JButton b is a copy or clone of the JButtons in buttons, but I'm struggling for an explanation.

Any suggestions would be welcome.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 6 2009
Added on Nov 8 2009
6 comments
618 views