答案是我的問題在JFrame中借鑑了很多相同的對象從類
我想了很多「阿泰」的對象在框架的底部寫的。我嘗試了很多例子,但總是失敗。
在這種情況下,我想看到很多正在離開的矩形。但是,只有一個,它會越來越快...
它不會同時顯示多個對象。你能告訴我有什麼問題嗎?
我用這個代碼:
public class GamePanel extends JPanel
{
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.BLACK);
for(Ates a1 : StartGame.alist) // alist is an arraylist for Ates class objects
{
g.fillRect(a1.getX(), a1.getY(), 20, 20);
}
...
實施例創建:
public void sentAtes()
{
r = rand.nextInt(471)+60;
Ates a = new Ates(r);
alist.add(a);
}
阿泰類:
public Ates(int a)
{
x = 700;
y = a;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setX(int a)
{
x = a;
}
public void setY(int a)
{
y = a;
}
StartGame類:
public class StartGame extends JFrame implements KeyListener, ActionListener
{
protected static ArrayList<Ates> alist = new ArrayList<Ates>();
public static int cen = 0;
...
public StartGame()
{
jp = new GamePanel();
add(jp);
...
int delay = 10;
ActionListener taskPerformed = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
cen++;
if(cen > 50)
{
cen = 0;
sentAtes();
}
for(Ates a1 : alist)
{
a1.setX(a1.getX()-1);
}
repaint();
}
};
new Timer(delay,taskPerformed).start();
...
信息:如果只有一個對象,它會像預期的那樣離開。
回答我的問題。
在Ates
類中,您不應該使用static
字作爲變量並使用this.
前綴來設置它們。
這應該是工作。
public class Ates extends JFrame
{
protected int x;
protected int y;
public Ates(int a)
{
this.x = 700;
this.y = a;
}
你把它們都畫在同一個地方? – james
你確定所有'Ates'有不同的* x *和* y *嗎?你確定'startGame.alist'有多個元素嗎? – Christian
向我們展示'alist'和它是如何創建的 –