Bouncing balls in Java Swing

This program displays several ball(more precisely “circles”) bouncing off the sides of the enclosing component.

Code 1:The JFrame class (Main window)

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class base_frame extends JFrame
{
	
	Container c;
	
	//our components
	JPanel b_panel;
	JButton b_add,b_sub;
	JLabel l_counter,l_ballsize;
	JTextField t_ballsize;
	
	//Actionlistener class instance
	handler handle;
	
	//class which contains drawing surface "JComponent"
	canvas ballcanvas;
	
	base_frame()
	{
		super("Ball Simulator");
		c=getContentPane();
		
		//setting to "flowlayout"
		c.setLayout(new FlowLayout());
		
		//all components
		t_ballsize=new JTextField(2);
		l_counter=new JLabel("Ball Count:  ");
		l_ballsize=new JLabel("Ball Size:  ");
		l_counter.setBorder(BorderFactory.createBevelBorder(1));
		b_add=new JButton("Add");
		b_sub=new JButton("Remove");
		handle=new handler();
		//adding actionlistener to buttons
		b_add.addActionListener(handle);
		b_sub.addActionListener(handle);
		
		//button panel 
		b_panel=new JPanel();//panel to hold buttons,textfields..
		b_panel.add(l_ballsize);//label
		b_panel.add(t_ballsize);//textfield to input ball size
		b_panel.add(b_add);//button to add a ball
		b_panel.add(b_sub);//button to del a ball (the most recent one)
		b_panel.add(l_counter);//label displaying total balls being rendered
		
		//ball canvas
		ballcanvas=new canvas(); 
		
		//container details
		c.add(ballcanvas);//adding drawing surface(ballcanvas) to main jframe
		c.add(b_panel);//adding the panel along with its smaller components
		
		//set visuals
		setSize(640,480);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	
	}
	public static void main(String[] args)
	{
		new base_frame();//creating main jframe instance
	}
	
	//an inner class to take care of button events
	class handler implements ActionListener
	{
		public void actionPerformed(ActionEvent ae)
		{
			//if "Add" button clicked
			if(ae.getSource()==b_add)
			{
				if(!t_ballsize.getText().equals(""))
				{
					
					try{
						ballcanvas.addBall(Integer.parseInt(t_ballsize.getText()));
						
						//updates the counter label
						l_counter.setText("Ball Count:"+ballcanvas.countBall());
					}catch(NumberFormatException e)
					{
						System.out.println(e);
						JOptionPane.showMessageDialog(null,"Enter only numbers!","Invalid Input",JOptionPane.INFORMATION_MESSAGE);
						
					}
					
				}
				else
				{
					JOptionPane.showMessageDialog(null,"Enter the ball size!","Input needed",JOptionPane.INFORMATION_MESSAGE);
				}
			}//b_add
			
			//if "Sub" button clicked
			if(ae.getSource()==b_sub)
			{
				ballcanvas.removeBall();
				//updates the counter label
				l_counter.setText("Ball Count:"+ballcanvas.countBall());
			}
		}
	}
}

Code 2:The drawing surface class .JComponent used

import java.awt.*;
import javax.swing.*;
import java.util.*;
public class canvas extends JComponent
{
	//display details	
	private final int width=512;
	private final int height=384;
	
	//ball array
	final private ArrayList<ball> ball_array;
	
	canvas()
	{
		ball_array=new ArrayList<ball>();
		
		setPreferredSize(new Dimension(width,height));
		setBorder(BorderFactory.createEtchedBorder(1));
	}
	
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		g.setColor(Color.BLACK);
		
		//fill rect
		g.fillRect(0,0,getWidth(),getHeight());
		try
		{
			//draw balls from ball_array
			for(int i=0;i<ball_array.size();i++)
			{
				ball_array.get(i).drawBall(g);
				//System.out.println("Drawing ball");
			}
			Thread.sleep(5);//to control animation speed

		}catch(InterruptedException e)
		{
			System.out.println("cannot control the paint thread!!");
		}
		repaint();//calls the paint method 
	}
	
	//to add a ball
	public void addBall(int size)
	{
		ball_array.add(new ball(size));
	}
	
	//to remove a ball
	public void removeBall()
	{
		if(!ball_array.isEmpty())
		{
			ball_array.remove(ball_array.size()-1);
		}
		
	}
	
	//return total balls from the array
	public int countBall()
	{
		return ball_array.size();
	}
	
	//Ball inner-class
	class ball
	{
		private int x_pos=0;
		private int y_pos=0;
		private int dir_x=1;
		private int dir_y=1;
		private int size;
		
		ball(int size)
		{
			this.size=size;
		}
		
		private void calculate_direction()
		{
			//move the ball
			x_pos=x_pos-dir_x;
			y_pos=y_pos-dir_y;
			
			//for X-direction
			if(x_pos<0)
			{
				x_pos=0;
				dir_x=-1;//incr
			}
			else
			if(x_pos+size>getWidth())
			{
				dir_x=1;//decr
			}
			
			//for Y-direction
			if(y_pos<0)
			{
				y_pos=0;
				dir_y=-1;//incr
			}else
			if(y_pos+size>getHeight())
			{
				dir_y=1;//decr
			}
		}
		
		public void drawBall(Graphics g)
		{
			calculate_direction();
			g.setColor(Color.WHITE);
			g.drawOval(x_pos,y_pos,size,size);
		}
	}
}

Download the jar file : Ball Simulate

About PraveenMax
My Interests: ------------------ Programming , Drawing & Music

3 Responses to Bouncing balls in Java Swing

  1. ravi says:

    nice, ur doing well.
    i am at starting level of swings ,can u plz tell me send me a “swings concept book”

  2. anju boura says:

    sir u r inspiration to us

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: