简体   繁体   中英

Pass Dynamically Created ArrayList<JButton> Index to ActionListener Class

First off thanks for everyone who contributes. It's such a lifesaver. That said, here's my first ever post.

I've created a dynamic array of JButton objects and attached an ActionListener to the button.

public void printFound(ArrayList<Customer> found)
{       
    buttons = new ArrayList();
    texts = new ArrayList();
    for(Customer temp: found)
    {
        JButton btn = new JButton("Edit");
        btn.addActionListener(new PushEdit());
        btn.setPreferredSize(new Dimension(100, 40));
        panel1.add(btn);
        buttons.add(btn);
        JTextArea text = new JTextArea(temp.toString(), 8, 80);
        text.setLineWrap(true);
        panel1.add(text);
        texts.add(text);
    }
} 

When I click on an edit button, I want it to pass the index of "btn" in "buttons" to the ActionListener so that I can display the values in "temp" in another GUI. I figure I either need to pass temp directly or I need to pass both the index of "btn" as well as the index of "found".

Thanks!

as i can understand from your question you want to get the index of the jbutton that stored in buttons ArrayList to do some sort of things..

to do this you can use setActionCommand and getActionCommand methods to bind a String along with every jbutton that created and

so your code will be like this

public void printFound(ArrayList<Customer> found)
{       
    buttons = new ArrayList();
    texts = new ArrayList();
    Integer index=0;
    for(Customer temp: found)
    {
        JButton btn = new JButton("Edit");
        btn.setActionCommand(index.toString());
        btn.addActionListener(new PushEdit());
        btn.setPreferredSize(new Dimension(100, 40));
        panel1.add(btn);
        buttons.add(btn);
        JTextArea text = new JTextArea(temp.toString(), 8, 80);
        text.setLineWrap(true);
        panel1.add(text);
        texts.add(text);

        index=index+1;
    }
} 

whenever you you want to get the index

System.out.print(btn.getActionCommand());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM