Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用for循环将项添加到ArrayList会引发outofbounds异常_Java_Swing_For Loop_Button_Arraylist - Fatal编程技术网

Java 使用for循环将项添加到ArrayList会引发outofbounds异常

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();

我试图向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();
            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。哦,我误解了容量和大小是一样的。谢谢。没问题,我也多次犯过这种错误。”。