java.lang.ArrayStoreException 使用新的 JPanel

java.lang.ArrayStoreException with new JPanel

我有一个问题:

public static JPanel regNewBodyPart(int i, int x, int y){

    //System.out.println(i);

    body[i] = new SnakeBlock();
    JPanel bp = body[i];
    //bp.setBackground(Color.GREEN);
    bp.setBounds(x, y, 20, 20);
    bp.setVisible(true);
    registeredBodyParts++;

    return(bp);

}

当我更改

时抛出一个 java.lang.ArrayStoreException

body[i] = new SnakeBlock();body[i] = new Block(); 没有。

我没有做错什么..

SnakeBlock()Block()类很相似!

蛇形方块/方块:

public class Block /* /SnakeBlock */ extends JPanel{

    public Block() /* /SnakeBlock */{

    }

    @Override
    protected void paintComponent(Graphics g){ 
        super.paintComponent(g);    
    } 
}

参见API

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:

Object x[] = new String[3];
x[0] = new Integer(0);

要避免此异常,请将 body 数组定义为适当的数据类型,例如:

JPanel[] body = new JPanel[n];