晚上好。我正在開發一款類似於老遊戲LiteBrite的程序,在該程序中,您將彩色掛釘放置在面板上並點亮。在我的程序中,它的作用類似於當你點擊面板時,它將創建一個新的Ellipse(其名稱爲ColorEllipse,它具有位置,大小和顏色的規格),並將其存儲起來以進行保存。目前它是一個數組列表,但我需要它是一個常規數組。我被告知將創建一個新數組的方式,並將舊數組的所有內容複製到新數組中。現在我使用的是數組列表,但毫無疑問,這個程序有我們需要使用常規數組的規範。添加/刪除元素時創建新的數組?
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,但我需要它是在這個規範的規則陣列。然後當面板被點擊時,它會在該特定位置的Array中添加一個新的ColorEllipse(並根據需要重新繪製以顯示)。該計劃的後期部分將是當我觸摸已經放置的釘,它將其刪除,但那是另一次。現在我需要知道如何增加數組的大小並將其內容複製到數組中。任何人都可以告訴我我應該改變什麼?
如果OP在所有'洞'中放置'釘',那麼陣列無論如何都將處於最大尺寸。我個人並不明白爲什麼陣列需要首先調整大小。 – Radiodef
我同意,這似乎是一個不必要的優化,最糟糕的情況是,他將不得不填補大部分(如果不是整個)董事會和宣佈全數組然後可以忽略不計。 – arynaq