participate


Swing - Add actionlistener to JButtons in a collection
This question is answered.

<<   Back to Forum  |   Give us Feedback
5 Duke Stars available
This topic has 6 replies on 1 page.
Martin_J
Posts:99
Registered: 1/14/08
Add actionlistener to JButtons in a collection   
Nov 7, 2009 9:23 PM
 
 
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.
 
DarrylBurke
Posts:15,598
Registered: 7/2/07
This Thread is now moved   
Nov 7, 2009 9:32 PM (reply 1 of 6)  (In reply to original post )
 
 
Note: This thread was originally posted in the Java Programming forum, but moved to this forum for closer topic alignment.
 
Encephalopathic
Posts:13,714
Registered: 12/20/07
Re: Add actionlistener to JButtons in a collection   
Nov 7, 2009 9:36 PM (reply 2 of 6)  (In reply to original post )
 
 
Hmmm, I can't tell where the problem is based on the code as presented, so perhaps the problem lies elsewhere. I think that your best bet here is to show us your problem in a way that we can actually see and work with. You should consider condensing your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:

http://homepage1.nifty.com/algafield/sscce.html

Much luck!
 
DarrylBurke
Posts:15,598
Registered: 7/2/07
Re: Add actionlistener to JButtons in a collection      
Nov 7, 2009 9:46 PM (reply 3 of 6)  (In reply to original post )
Helpful
 
To get better help sooner, post a SSCCE that clearly demonstrates your problem.

The only thing I can think of is that JButton b is a copy or clone of the JButtons in buttons
The variable in a for-each loop (aka enhanced-for loop) is a local variable. Assigning a new instance to the variable will have no impact on the object in the collection being iterated over; however, calling methods (as evinced in your code) will invoke those methods on the same instance.

db

edit For example, this SSCCE shows there is no problem with the parts of code you posted.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
 
public class ListOfButtons {
 
  List<JButton> buttons;
 
  public ListOfButtons(int count) {
    buttons = new ArrayList<JButton>(count);
    for (int i = 0; i < count; i++) {
      buttons.add(new JButton("Button " + i));
    }
  }
 
  public List<JButton> getButtons() {
    return buttons;
  }
 
  public void makeUI() {
    ActionListener listener = new ActionListener() {
 
      @Override
      public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, ((JButton) e.getSource()).getText());
      }
    };
 
    JPanel panel = new JPanel(new GridLayout(0, 1));
    for (JButton button : getButtons()) {
      button.addActionListener(listener);
      panel.add(button);
    }
 
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
 
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
 
      @Override
      public void run() {
        new ListOfButtons(6).makeUI();
      }
    });
  }
}


Edited by: DarrylBurke
 
Martin_J
Posts:99
Registered: 1/14/08
Re: Add actionlistener to JButtons in a collection   
Nov 7, 2009 10:15 PM (reply 4 of 6)  (In reply to #3 )
 
 
Daryl,

Thanks for the reply.

I may give the SSCCE a try.

Before I do, I'll try to spot the difference between your code and mine. Has it got anything to do with the fact that your code adds the button to the panel after assigning the actionListener, but my code adds it to the panel before assigning the actionListener? Does the sequence make a difference?
 
DarrylBurke
Posts:15,598
Registered: 7/2/07
Re: Add actionlistener to JButtons in a collection   
Nov 7, 2009 10:27 PM (reply 5 of 6)  (In reply to #4 )
 
 
Does the sequence make a difference?
It's trivial to try it and find out for yourself. Why do you think it might make a difference?

db
 
Martin_J
Posts:99
Registered: 1/14/08
Re: Add actionlistener to JButtons in a collection   
Nov 7, 2009 11:14 PM (reply 6 of 6)  (In reply to #5 )
 
 
Aaarrgghh...

Found it.

I had called an "assemblePanel" method twice, so when I called a "getPanel" method, the code would recreate an exact duplicate of the panel, except for the assigned actionListeners.

Thanks for your attention anyway.
 
This topic has 6 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 54
  • Guests : 135

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums