[英]Pass Dynamically Created ArrayList<JButton> Index to ActionListener Class
首先感谢所有贡献者。 真是救命稻草。 也就是说,这是我的第一篇文章。
我创建了一个动态的JButton对象数组,并将ActionListener附加到该按钮。
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);
}
}
当我单击编辑按钮时,我希望它将“按钮”中的“ btn”索引传递给ActionListener,以便可以在另一个GUI中的“ temp”中显示值。 我认为我要么需要直接传递temp,要么需要传递“ btn”的索引以及“ found”的索引。
谢谢!
正如我从您的问题中可以理解的那样,您想要获取存储在buttons ArrayList
中的jbutton
的索引,以执行某种操作。
为此,您可以使用setActionCommand
和getActionCommand
方法将String与创建的每个jbutton
绑定在一起,并
所以你的代码会像这样
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;
}
}
每当您想要获取索引时
System.out.print(btn.getActionCommand());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.