first of all, thanks for the suggestions lately where im asking to avoid flicking of the ball.. now its working smoothly :)) but i want now to add some more balls.. like 2 - 3 balls.. how can i do that ? i dont have an idea.. thanks guys..

Recommended Answers

All 10 Replies

Standard approach (very short version):
Ball class implements a single Ball, including its position, velocity etc, and has a public method to draw the ball on a Graphics that is passed as a parameter.
Main class has a window where things are displayed. Creates new Balls on request, and adds them to a List of Balls. Its paintComponent(Graphics g) calls the drawing method for every Ball in the List.

thanks but, im sori if i dont understand well your guide. Do you want to say, create many class (every class = ball) then call single method for them all?

Here are some pieces of code that illustrate how to put this all together. Don't take them literally - just understand what they are doing and create your own version.

public class Ball { 
  int x, y, xVelocity, yVelocity;  Color ballColor;  // etc etc
  ...
  public paintMe(Graphics g) {
     // code to draw this one ball on Graphics g goes here
  }
  ...
}

public class MainWindow {
  ...
  private ArrayList<Ball> allBalls = new ArrayList<Ball>();
  ...
  public void addBall() { // add a new Ball to the window
    allBalls.add(new Ball());
  }
  ...
  public void paintComponent(Graphics g) {
    for (Ball b : allBalls) {  
      // paint each Ball on the window's Graphics
      b.paintMe(g);
    }
  }
  ...
}

im not familiar with "arraylist<blabla>" :|, i guess i have to review this over and over again. Thanks.

An ArrayList<Ball> is like an array of Balls except that it grows and shrinks to fit the number of Balls in it at any time. Experienced Java programmers will use ArrayList (or one of the other similar classes) rather than arrays because you don't have to worry about getting the size right.
The for (Ball b : allBalls) { loop just loops through all the Balls in the ArrayList - it's normally called a for/each loop and is spoken as "for each Ball b in allBalls".

In your code you don't have to use ArrayList if you don't want to - you can just create a big-enough array of Balls, and have a variable to keep track of how many Balls there are in the array.

oh thanks! :) i got a question, what are the types that we can put in : ArrayList<here>someName
?? And, is it also same as : Ball allBalls[] = new Ball[30]; ??

The thing in <> is the type(s) you can put in the ArrayList, as in
ArrayList<Ball> - is a list that contains only Balls.

It's just like Ball allBalls[] = new Ball[30]; except that the size varies to fit the data.

the Ball in the <> is a class right?? so you can put class or string there.. how about other type? or how many types we can put in <> ?? haha sorry poor english..

hi JamesCherrill, i try my best but its not working still..

import javax.swing.*; // For JPanel, etc.


import java.util.ArrayList;
import java.util.Random;
import java.awt.*;           // For Graphics, etc.
import java.awt.event.*;
import java.awt.geom.*;      // For Ellipse2D, etc.
import java.io.*;
public class aball extends JFrame
{
	ArrayList<Balls> allBalls;
	public aball()
	{
		setTitle("Bouncing Ball");
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		panel.add(new Balls());
		add(panel);
		setSize(400,400); //W x H
		setVisible(true);
		setLocationRelativeTo(null);
		ArrayList<Balls> allBalls = new ArrayList<Balls>();
		repaint();
	}// end constructor
	
	public void addBalls()
	{
		allBalls.add(new Balls());
		repaint();
	}
	
	public void paintComponent(Graphics g)
	{
		try{
			addBalls();
			System.out.println("!");
		Thread.sleep(4000);
		Balls balls = new Balls();
		balls.paintMe(g);
		}catch(Exception ex){}
		
	}
	
	
	public static void main(String[] args)
	{
			aball ok = new aball();
			
		
	}// end main
	
	
}// end class

class Balls extends JPanel
{
	static int x, y;
	static int directionX =2;
	static int directionY = 2;
	static int widx;
	public Balls()
	{
		
		Thread gameThread = new Thread()
		{
			public void run()
			{
				while(true)
				{
					x += directionX;
					y += directionY;
					if(x < 0)
					{
						x = 0;
						directionX = -directionX;
						System.out.println(x);
					}
					else if(x > getWidth() - 50)
					{
						x = getWidth() - 50;
						directionX = -directionX;
					}
					
					if(y < 0)
					{
						y = 0;
						directionY = -directionY;
					}
					else if(y > getHeight() - 50)
					{
						y = getHeight() - 50;
						directionY = -directionY;
					}
					repaint();
					
					try
					{
						Thread.sleep(new Random().nextInt(30) + 1);
					}catch(Exception ex){}
				}
			}
		};
		gameThread.start();
	}
	

	public void paintComponent(Graphics g)
	{
		paintMe(g);
	}
	
	public void paintMe(Graphics g)
	{
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;
		g2.setColor(Color.GREEN);
		g2.fillRect(0, 0, getWidth(), getHeight());
		g2.setColor(Color.PINK);
		g2.fillOval(x,y,50,50);

	}
	
	
}

please tell me where i did go wrong

Ball shouldn'd extend anything - it's just a Ball. Call it Ball, not Balls because each instance represents just one ball. Also rename your main class - call it something like BouncingBalls so we can all understand what it does.
Keep all the code for changing x,y, direction etc in a method in the Ball class eg moveMe(), but move the main loop into the main class so it looks like

public void run() {
  while(true) {
    for (Ball b : allBalls) {
      b.moveMe(g);
    }
    // repaint, wait, loop

You public void main can then look like:

BouncingBalls bb = new BouncingBalls ();
bb.addBall();
bb.addBall(); // two balls now

Finally: main class paintComponent like my previous example code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.