Java Bouncing Ball

前端 未结 4 1575
天涯浪人
天涯浪人 2020-11-22 04:57

I am trying to write a Java application which draws multiple balls on screen which bounce off of the edges of the frame. I can successfully draw one ball. However when I add

4条回答
  •  盖世英雄少女心
    2020-11-22 05:44

    What you need to do is augment your paintComponent method.

    Instead of just drawing one ball, you need to loop through them all, and draw each one.

    Example:

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        for (Ball b: balls) {
            g.setColor(color);
            g.fillOval(x,y,30,30); //adds color to circle
            g.setColor(Color.black);
            g2.drawOval(x,y,30,30); //draws circle
        }
    }
    

提交回复
热议问题