是否可以检索字符串数组的索引?在爪哇
我用Java和swing编写了一个计算器,所以我有了这个数组
private String[] array = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", "=", "C", "+", "-", "*", "/"};
我将这个数组传递给我的方法:
private JPanel init(String[] tab) {
JPanel c = new JPanel ( new GridLayout( 5,1));
for (String e : tab)
{
values = new JButton(e);
values.addActionListener(this);
c.add(values);
System.out.println(e);
}
return c;
}
问题是,在我的addActionListener中,我只从我的表中获取文本,所以你告诉我这很好,但我还需要在单击时获取索引,因为我想将其用于操作符,以区分所有这些
我仍在寻找解决方案,但到目前为止我还没有找到。 以下是我的ActionListener的代码:
public void actionPerformed(ActionEvent e) {
System.out.println(((AbstractButton) e.getSource()).getText());
value = ((AbstractButton) e.getSource()).getText();
}
# 1 楼答案
到目前为止,您已经在JPanel中设置了所有按钮,现在您应该这样做
在你点击的按钮上
由于每次单击按钮时都必须检查事件源,因此我建议使用匿名内部类作为侦听器,这样就不必检查事件源
按^{的方式做
作为匿名的内部阶级
button.setActionListener(new ActionListener(){ @Override public void actionPerformed(Action event) { your code here}});
对每个按钮都这样做,那么你就不必按按钮了。getSource()因此增加了按钮点击的响应时间
# 2 楼答案
ArrayList中特定元素的索引可以使用java方法获得。util。ArrayList。indexOf()
你可以在这里看到一个例子:
https://www.tutorialspoint.com/get-the-index-of-a-particular-element-in-an-arraylist-in-java