import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class LiteBritePanel extends javax.swing.JPanel{
private final static int OFFSET = 5;
private static int LINE_WIDTH = 2;
private static int CELL_WIDTH = 25;
public ArrayList <Colorable> _circles; // where ColorEllipses will be stored
private ButtonPanel controlpanel; // used to set the color of peg that will be placed
public LiteBritePanel() {
this.setBackground(java.awt.Color.black);
_circles = new ArrayList<Colorable>();
controlpanel = new ButtonPanel(this);
this.addMouseListener(new MyMouseListener(this));
this.add(controlpanel);
}
public void paintComponent(java.awt.Graphics aPaintBrush) {
super.paintComponent(aPaintBrush);
java.awt.Graphics2D pen = (java.awt.Graphics2D) aPaintBrush;
java.awt.Color savedColor = pen.getColor();
pen.setColor(java.awt.Color.black);
for (int ball=0;ball<_circles.size();ball++)
if(_circles.get(ball).isEmpty())
return;
else
_circles.get(ball).fill(pen);
pen.setColor(savedColor);
this.repaint();
}
public void mouseClicked(java.awt.event.MouseEvent e){
boolean foundSquare = false;
for (int ball=0; ball < _circles.size() && !foundSquare; ball++){
if (_circles.get(ball).contains(e.getPoint()) == true){
foundSquare = true;
_circles.remove(ball);
this.repaint();
}
}
}
private class MyMouseListener extends java.awt.event.MouseAdapter {
private LiteBritePanel _this;
public MyMouseListener(LiteBritePanel apanel){
_this = apanel;
}
public void mouseClicked(java.awt.event.MouseEvent e){
_circles.add(new ColorEllipse(controlpanel.getColor(), e.getPoint().x - (e.getPoint().x%CELL_WIDTH), e.getPoint().y - (e.getPoint().y%CELL_WIDTH), CELL_WIDTH-3,_this));
_this.requestFocus();
boolean foundSquare = false;
for (int ball=0; ball < _circles.size() && !foundSquare; ball++){
if (_circles.get(ball).contains(e.getPoint()) == true){
foundSquare = true;
// code for removing ball if one is placed
_this.repaint();
}
}
}
}
}`
现在它被设置为Arraylist,但我需要它按照这个规范在常规数组中。然后在单击面板时,它会在该特定位置向该阵列添加一个新的ColorEllipse(并根据需要进行重新绘制以显示它)。该程序的后期部分将是当我触摸已经放置的挂钉时,它将其移除,但那是另一次。现在我需要知道如何增加数组的大小并将其内容复制到其中。有人能告诉我应该改变什么吗?
答案 0 :(得分:1)
要复制数组,可以使用System.arraycopy(...)方法(System API):
public static void arraycopy(
Object src,
int srcPos,
Object dest,
int destPos,
int length)
你首先要创建一个目标数组,可能是源数组的两倍,并传递旧数组,起始索引(0),新数组,目标起始索引(0),长度(旧阵列的长度),它应该完成其余的工作。
另外你不想在paintComponent中调用repaint,相信我。请改用Swing Timer。谷歌可以帮助您找到一个很好的教程。
答案 1 :(得分:0)
根据您的电路板的大小,您可以创建一个与电路板尺寸相同的阵列。或者你可以像Hovercraft建议的那样做,但这完全取决于你是否想用cpu换取内存。
int MAX_POSSIBLE_ELEMENTS = ...
Colorable[] _circles = new Colorable[MAX_POSSIBLE_ELEMENTS];
....rest of code...
请注意,最大数量取决于电路板的高度和宽度,因此您应该在编译时知道这一点。