有谁知道如何将ActionListener添加到一个按钮数组?

huangapple go评论65阅读模式
英文:

Does anyone know how to add ActionListener to an array of buttons?

问题

我正在创建一个项目,类似于Mancala(一种棋盘游戏)。我使用循环将ActionListener添加到按钮数组中,并调用各自的处理程序。在第一次运行时,我以为一切都很正常,GUI显示出来了,但当我点击按钮时,虽然GUI能正常工作,但命令行界面却显示了许多错误信息。第二次运行相同的代码时,GUI不再显示,命令行界面显示:

主异常:java.lang.ArrayIndexOutOfBoundsException:8

(还有其他内容。)

以下是我的代码:

Handler handler = new Handler();
for (int i = 0; i <= 8; i++) {
    btnPods[i].addActionListener(handler);
}

这样写对吗?

英文:

I'm creating a project and its similar to mancala. I add ActionListener to an array of buttons with a loop and call the separated handler. At first run I thought it was okay, GUI shows up but when I clicked buttons it was working but the CLI says a lot of errors. On the second running, same code the GUI doesn't show up anymore and CLI says:

Exception in main java lang.ArrayIndexOutOfBoundsException:8

(And other stuff.)

Here's my code:

Handler handler = new Handler();
for( int i = 0; i&lt;=8; i++ )
{btnPods[i].addActionListener( handler ); }

Is this right?

答案1

得分: 0

我找到了问题。它超出了边界,因为条件是<= 8,它从0开始,所以应该是<= 7或< 8。我把它改成了i<= 7。但还有其他方法可以向按钮添加addActionlistener吗?还是我所做的方法可以?

我目前是新手,正在寻找热心的人来回应,我真的在寻找很多答案。

英文:

Ooh.. I've found the problem. Its out of bounds because the condition is <= 8 it starts at 0 so it should be <= 7 or < 8. I changed it to i <= 7. But is there any other ways to addActionlistener to a button or what I did is fine?

I'm currently new here and I'm looking for lovely people to respond, I'm really searching for a lot of answers

答案2

得分: 0

自Java 1.5版本(很久以前)开始,您可以使用for-each循环,这将使您不必考虑数组索引:


JButton [] btnPods = ...
Handler handler = new Handler();

for(JButton btnPod : btnPods) {
    btnPod.addActionListener(handler);
}
英文:

Since java 1.5 (read since long time ago) you can use for-each loop, this will save you from thinking about the array indices:


JButton [] btnPods = ...
Handler handler = new Handler();

for(JButton btnPod : btnPods) {
    btnPod.addActionListener(handler);
}

huangapple
  • 本文由 发表于 2020年4月4日 07:26:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/61021861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定