【问题标题】:How do I create multiple objects of the same class?如何创建同一类的多个对象?
【发布时间】: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++...

标签: java swing


【解决方案1】:

n 的值永远不会在您的代码中更改。所以addObject 将始终将新对象放在actor 数组的索引0 中。

【讨论】:

  • 我只是注意到了,但我已经用 n++ 多次尝试过;在 addObject 方法中
【解决方案2】:

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

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

并更改 addObject() 方法以将对象添加到演员数组

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多