简体   繁体   English

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

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

I'm creating a project and its similar to mancala.我正在创建一个项目,它类似于 mancala。 I add ActionListener to an array of buttons with a loop and call the separated handler.我将ActionListener添加到带有循环的按钮数组中并调用分离的处理程序。 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.在第一次运行时,我认为没问题,GUI 出现了,但是当我单击按钮时它正在工作,但 CLI 显示了很多错误。 On the second running, same code the GUI doesn't show up anymore and CLI says:在第二次运行时,GUI 不再显示相同的代码,CLI 显示:

Exception in main java lang.ArrayIndexOutOfBoundsException:8

(And other stuff.) (和其他东西。)

Here's my code:这是我的代码:

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

Is this right?这是正确的吗?

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?它超出了范围,因为条件是 <= 8 它从 0 开始,所以它应该是 <= 7 或 < 8。我将其更改为 i <= 7。但是有没有其他方法可以将addActionlistener添加到按钮或我做了什么好吗?

I'm currently new here and I'm looking for lovely people to respond, I'm really searching for a lot of answers我目前是新来的,我正在寻找可爱的人来回应,我真的在寻找很多答案

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:由于 java 1.5(很久以前读过),您可以使用 for-each 循环,这将使您无需考虑数组索引:


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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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