【发布时间】:2018-05-16 08:20:02
【问题描述】:
我正在尝试将多个 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);
为什么这里会出现 outofbounds 异常?我认为 ArrayLists 是动态的,并且无论如何都以 10 的初始容量开始。
【问题讨论】:
-
docs.oracle.com/javase/8/docs/api/java/util/…。 Java 中的索引从 0 开始。而且你甚至不应该使用这个 add() 方法。只需使用 add() 方法,只接受一个对象作为参数。
-
感谢您将我引导到我已经看过的文档,但我不明白为什么您向我展示的内容可以解释问题。
-
它说:“抛出 IndexOutOfBoundsException - 如果索引超出范围 (index size())”。列表最初的大小是多少? 0. 你的第一个索引是什么? 1. 1 > 0?是的。所以它会抛出一个 IndexOutOfBoundsException。
-
哦,我把容量和大小误解为同一个东西。谢谢。
标签: java swing for-loop button arraylist