在数组中遇到问题

时间:2012-12-07 23:44:31

标签: java arrays methods

我正在尝试添加和删除数组中的球,我只允许使用数组(不是arraylist)。 我在添加和删除球方法时遇到问题,并且在添加和删除球方法的长度上不断出现“插入”AssignmentOperator Expression“”错误。不知道如何解决问题。 帮助赞赏。

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));

         }

     }
 }

}

1 个答案:

答案 0 :(得分:0)

我不确定我理解你的问题,因为你没有很好地指明你得到错误的地方,但看起来好像你将myBalls声明为25个元素的数组,但是然后在构造函数中正在为它分配一个零元素的新数组。您无法向零元素数组添加任何内容。