2012-12-07 192 views
0

我想添加和删除数组到球中,我只允许使用数组(不是数组列表)。 我遇到了添加和删除球方法的问题,并不断收到一个“插入”AssignmentOperator表达式“”添加和删除球方法的长度错误。不知道如何解决这个问题。 帮助赞赏。遇到数组中的方法问题

private final int DIAMETER = 60; 
private java.awt.Color _currentColor; 
//private SmartEllipse _ball; 

SmartEllipse [] myBalls = new SmartEllipse [25]; 


public BallPanel() { 

    super(); 
    this.setBackground(java.awt.Color.white); 

    myBalls = new SmartEllipse[0]; 

    _currentColor = java.awt.Color.red; 

    this.addMouseListener(new MyMouseListener()); 


} 

//translate the click coordinates to a grid coordinate 
    public java.awt.Point translatePoint(java.awt.Point aPoint) 
    { 

     int x = aPoint.x; 
     int y = aPoint.y; 

     aPoint.x = x/20; 
     aPoint.y = y/20; 

     return aPoint; 

    } 


    //find a ball in the array 
    public int findBall(java.awt.Point p) 
    { 
     for (SmartEllipse se : myBalls) 
     {  
      java.awt.Point translatedPoint = translatePoint(se.getLocation()); 

      if (translatedPoint.x == p.x && translatedPoint.y == p.y) 
       return myBalls.length; 
     } 

     return -1; 

    } 

    // remove a ball from the array 
    public void removeBall(SmartEllipse p) 
    { 
     myBalls.length-1; 
     this.repaint(); 
     this.revalidate(); 
    } 

    //add a peg to the array 
    public void addBall(SmartEllipse p) 
    { 
     myBalls.length; 
     this.repaint(); 
     this.revalidate(); 
    } 


public void paintComponent(java.awt.Graphics aBrush) 
{ 
     super.paintComponent(aBrush); 
     java.awt.Graphics2D betterBrush = (java.awt.Graphics2D) aBrush; 

     for (SmartEllipse se : myBalls) 
     { 
      se.draw(betterBrush); 
      se.fill(betterBrush); 
     } 
} 



private class MyMouseListener extends javax.swing.event.MouseInputAdapter 
{ 
    public void mouseClicked(MouseEvent e) 
    { 
     // get X and Y of click 
     // translate X and Y to grid 
     // check peg array for duplicate 
     // if duplicate, remove ball 
     // else add ball to ball array 

     java.awt.Point p = translatePoint(e.getPoint()); 

     // Adjust the coordinates 


     int index = findBall(p); 

     for (int i = 0; i< myBalls.length; i++) 
     { 


      myBalls[i] = null; 


     if (index != -1) 
      remove(myBalls.length); 
     else 
      addBall(new SmartEllipse(_currentColor, p.x, p.y)); 

     } 

    } 
} 

}

+0

我很乐意帮助你,但我需要一些澄清。当你添加一个球时,它会进入阵列中的特定插槽,还是仅仅在阵列的末尾?同样的东西去除?每个球是否有一个分配的插槽,或者你只是随机添加和删除它们? –

回答

0

我不知道我理解你的问题,因为你不指定很好的你在哪里得到的错误,但它看起来好像您声明myBalls作为数组25个元素,但是然后在构造函数中为它分配一个新的零元素数组。您不能将任何内容添加到零个元素的数组中。

+0

好的。对于removeBall和addBall方法,我都在myBall.length处收到错误。此外,我希望我的应用程序以不包含任何球的屏幕开始,但是我希望该阵列可以容纳25个球。 –

+0

删除此行“myBalls = new SmartEllipse [0];”你的数组已经被声明为最多包含25个球,并且因为你没有添加任何球,所以它是空的。 – palako