我正在尝试将球添加和删除到数组中,我只被允许使用数组(而不是数组列表)。我在添加和删除球方法时遇到问题,并且在添加和删除球方法的长度上不断收到“插入”赋值运算符表达式“”错误。不知道如何解决问题。帮助表示赞赏。
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));
}
}
}
}