ArrayList删除不起作用

Ere*_*ren -2 java arraylist

我试图walls ArrayList用for循环删除里面的所有对象,但我不能让它工作

public void initializeButtons(){
    JButton save_button = new JButton("Save");
    save_button.addMouseListener(new Button_MouseListener(save_button));
    save_button.setBounds(1300, 50, 75, 50);
    add(save_button);

    JButton load_button = new JButton("Load");
    save_button.addMouseListener(new Button_MouseListener(load_button));
    load_button.setBounds(1300, 125, 75, 50);
    add(load_button);

    JButton reset_button = new JButton("Reset");
    save_button.addMouseListener(new Button_MouseListener(reset_button));
    reset_button.setBounds(1300, 200, 75, 50);
    add(reset_button);
}
Run Code Online (Sandbox Code Playgroud)

这是Button_MouseListener负责处理"Reset"按钮的一部分

if (button.getText().equals("Reset")) {
    for (int i = 0; i < walls.size(); i++) {
        walls.remove(((int)i));
    }
    repaint();
}
Run Code Online (Sandbox Code Playgroud)

注意: walls.clear();也不起作用,我没有收到任何错误.它什么都不做.

Era*_*ran 7

它看起来像复制粘贴错误.当你复制

JButton save_button = new JButton("Save");
save_button.addMouseListener(new Button_MouseListener(save_button));
save_button.setBounds(1300, 50, 75, 50);
add(save_button);
Run Code Online (Sandbox Code Playgroud)

您只在声明中更改了引用的名称

JButton load_button = new JButton("Load");
Run Code Online (Sandbox Code Playgroud)

但忘记在下面的行中更改它

save_button.addMouseListener(new Button_MouseListener(load_button));
Run Code Online (Sandbox Code Playgroud)

这意味着你仍然只是添加一个监听器save_button,而不是load_button.

同样的事情发生在reset_button这意味着代码

if (button.getText().equals("Reset")) {
    for (int i = 0; i < walls.size(); i++) {
        walls.remove(((int)i));
    }
    repaint();
}
Run Code Online (Sandbox Code Playgroud)

永远不会被这个按钮执行.

顺便说一下,这个循环毫无意义.如果您想清除List,请调用clear()方法.

walls.clear();
Run Code Online (Sandbox Code Playgroud)

你的循环无法正常工作的原因(即使你修复了侦听器问题)是walls.remove(i)删除i'th元素并使前者i+1的元素成为新i的第th个元素(它将所有元素i移到左后),这意味着你永远不会删除位置上的新元素,i因为在下一次迭代中i会增加.