【发布时间】:2018-08-29 13:30:35
【问题描述】:
我想创建 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();
}
}
当我运行这段代码时,我只会在我的框架中得到第一个“球”。我尝试了其他一些方法,但没有成功。
提前谢谢你。埃阿德里亚诺
【问题讨论】:
-
您永远不会更改您在
addObject方法中使用的n,因此您会不断覆盖旧创建的对象,并始终将所有内容放在actor数组的首位。 -
在某处添加
n++...