简体   繁体   中英

How do I create multiple objects of the same class?

I want to create two objects of the Ball class. I have tried the following:

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();
    }
}

When I run this code I only get the first 'ball' in my frame. I have tried some other things but without success.

Thank you in advance. ElAdriano

The value of n is never changed in your code. So addObject will always put the new object in index 0 of your actor array.

Change your Actor[] into ArrayList of type Actor this would help you forget about where to add the next object or at any index n

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

and change the addObject() method to add the object to the actors array

addObject(Actor a){
    actors.add(a);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM