带有新JPanel的java.lang.ArrayStoreException

时间:2015-06-11 18:51:10

标签: java swing exception 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()类相似!

SnakeBlock / Block:

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

    public Block() /* /SnakeBlock */{

    }

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

1 个答案:

答案 0 :(得分:3)

请参阅API

  

抛出此异常表示已尝试将错误类型的对象存储到对象数组中。例如,以下代码生成ArrayStoreException:

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

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

JPanel[] body = new JPanel[n];