Java 使用for循环将项添加到ArrayList会引发outofbounds异常
我试图向JButton数组列表中添加一些JButton,但是运行该代码会出现OutOfBounds异常。 以下是代码,摘自main方法:Java 使用for循环将项添加到ArrayList会引发outofbounds异常,java,swing,for-loop,button,arraylist,Java,Swing,For Loop,Button,Arraylist,我试图向JButton数组列表中添加一些JButton,但是运行该代码会出现OutOfBounds异常。 以下是代码,摘自main方法: ArrayList<JButton> buttonList = new ArrayList<JButton>(); for(int i = 1; i<=5; i+=1) { int j = i; JButton btn = new JButton();
ArrayList<JButton> buttonList = new ArrayList<JButton>();
for(int i = 1; i<=5; i+=1) {
int j = i;
JButton btn = new JButton();
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(j);
}
});
buttonList.add(i, btn);
mainPanel.add(buttonList.get(i));
System.out.println("Print "+i);
ArrayList按钮列表=新建ArrayList();
对于(inti=1;i这将对您有效
for(int i = 0; i<5; i+=1)
for(int i=0;i.索引在Java中从0开始。你甚至不应该使用这个add()方法。只需使用add()方法,将一个对象作为参数即可。虽然我很感激你指导我阅读我已经看过的文档,但我不明白为什么你向我展示的内容解释了这个问题。它说:“抛出IndexOutOfBoundsException-如果索引超出范围(索引<0 | |索引>大小())“。列表最初的大小是多少?0。你的第一个索引是什么?1.1>0吗?是的。因此它引发了IndexOutOfBoundsException。哦,我误解了容量和大小是一样的。谢谢。没问题,我也多次犯过这种错误。”。