我想添加和删除数组到球中,我只允许使用数组(不是数组列表)。 我遇到了添加和删除球方法的问题,并不断收到一个“插入”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));
}
}
}
}
我很乐意帮助你,但我需要一些澄清。当你添加一个球时,它会进入阵列中的特定插槽,还是仅仅在阵列的末尾?同样的东西去除?每个球是否有一个分配的插槽,或者你只是随机添加和删除它们? –