2

I have already made this program able to draw an instance of a small ball bouncing around a screen using these two classes

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;

import javax.swing.JPanel;
import javax.swing.Timer;

public class move extends JPanel implements ActionListener
{
    Timer t = new Timer(7, this);
    int x = 10, y = 10, velX = 7, velY = 7;

    public void paintComponent(Graphics g, Graphics h)
    {
        super.paintComponent(h);
        super.paintComponent(g);
        System.out.println(g);
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D circle = new Ellipse2D.Double(x, y, 40, 40);
        g2.fill(circle);
        t.start();
    }

    public void actionPerformed(ActionEvent e) {
        if(x<0 || x > getWidth())
        {
            velX = -velX;
        }
        if(y < 0 || y > getHeight())
        {
            velY = -velY;
        }
        x += velX;
        y += velY;
        repaint();
    }   
}

This class just simply draws the ball and provides the logic for the timer and such

import java.awt.Color;
import javax.swing.JFrame;

public class Gui {

    public static void main(String[] args)
    {
        move s = new move();
        JFrame f = new JFrame("move");
        f.add(s);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(1000, 1000);
        f.setTitle("Moving Circle");
        f.setBackground(Color.GREEN);
    }
}

This next class just puts it all in a JFrame, very simple stuff I know but I'm just trying to draw multiple instances within the same JFrame. I'm just trying to experiment with my knowledge of code, some sample of code to implement would be great.

How to draw multiple moving graphics?

Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
user1808763
  • 161
  • 2
  • 6
  • 10
  • 2
    `public void paintComponent(Graphics g, Graphics h)` And.. what calls that code? – Andrew Thompson Dec 25 '12 at 08:23
  • 2
    No doubt, you will love to go through [Kinetic Model](https://sites.google.com/site/drjohnbmatthews/kineticmodel), by @trashgod. – nIcE cOw Dec 25 '12 at 10:04
  • 2
    +1 GagandeepBali nice find. @user1808763 Also see this here for an example on some game logic: http://stackoverflow.com/questions/13999506/threads-with-key-bindings/14001011#14001011 – David Kroukamp Dec 25 '12 at 15:35

1 Answers1

5

This code could have a class Ball class that knows its position & size and how to draw itself to a Graphics.

As each ball is created, they are added to a list. At time of paint, iterate the list and paint each Ball.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433