![](/img/trans.png)
[英]How do I create multiple configurations for the same class with Configuration Admin?
[英]How do I create multiple objects of the same class?
我想創建Ball類的兩個對象。 我嘗試了以下方法:
public class World extends JPanel {
JFrame frame = new JFrame("GreenJ");
Actor[] actor = new Actor[100];
int n = 0;
public World() throws InterruptedException{
frame.add(this);
frame.setSize(1000, 1000);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void addObject(Actor a) {
actor[n] = a;
frame.add(actor[n]);
}
}
public class MyWorld extends World {
public MyWorld() throws InterruptedException {
addObject(new Ball(frame, 250, 750));
addObject(new Ball(frame, 750, 250));
}
}
public class Ball extends Actor{
int x;
int y;
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillOval(x, y, 50, 50);
}
public Ball(JFrame frame, int a, int b) throws InterruptedException{
frame.add(this);
x = a;
y = b;
}
public void main(String[]Args) {
repaint();
}
}
當我運行這段代碼時,我只會在框架中得到第一個“球”。 我嘗試了其他方法,但沒有成功。
先感謝您。 ElAdriano
n
的值永遠不會在您的代碼中更改。 因此, addObject
始終會將新對象放在actor
數組的索引0中。
改變你的Actor[]
進入ArrayList
類型的Actor
,這將幫助你忘記在哪里添加的下一個對象或任何索引n
ArrayList<Actor> actors = new ArrayList<>();
並更改addObject()方法以將對象添加到actors數組
addObject(Actor a){
actors.add(a);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.