[英]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.