Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何创建同一类的多个对象?_Java_Swing - Fatal编程技术网

Java 如何创建同一类的多个对象?

Java 如何创建同一类的多个对象?,java,swing,Java,Swing,我想创建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(1

我想创建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中。

代码中的
n
值从未更改。因此
addObject
将始终将新对象放在
actor
数组的索引0中。

actor[]
更改为
actor
类型的
ArrayList
这将帮助您忘记在何处添加下一个对象或在任何索引
n

ArrayList<Actor> actors = new ArrayList<>();

将您的
Actor[]
更改为
Actor
类型的
ArrayList
,这将帮助您忘记在何处添加下一个对象或在任何索引
n

ArrayList<Actor> actors = new ArrayList<>();

您永远不会更改
n
方法中使用的
addObject
,因此,您不断重写旧创建的对象,并始终将所有内容放在
actor
数组的第一位。add
n++
可能在某个地方重复…您永远不会更改
n
方法中使用的
n
,因此,您不断重写旧创建的对象,并始终将所有内容放在
actor
数组的第一位。add
n++
可能在某个地方重复…我刚刚注意到,但我已经用n++尝试了多次;在addObject方法中,我刚刚注意到了这一点,但我已经用n++尝试了多次;in-addObject方法