Showing posts with label Java Swing Bouncing Circle or Ball. Show all posts
Showing posts with label Java Swing Bouncing Circle or Ball. Show all posts

Friday, June 14, 2024

Bouncing Ball in Java Swing

// Bouncing Ball or Circle Swing

import java.awt.*;

import javax.swing.*;

import java.util.*;


public class BC extends JFrame

{

JFrame f;

JPanel p;

public BC()

{

f=new JFrame();

p=new JPanel()

{

int x=150;

int y=50;

int r=50;

int dx=11;

int dy=7;

 

public void paint(Graphics g)

{

Float r2,g1,b;

Random r1=new Random();

r2=r1.nextFloat();

g1=r1.nextFloat();

b=r1.nextFloat();

Color c=new Color(r2,g1,b);

g.setColor(c);

super.paintComponent(g);

g.fillOval(x-r,y-r,r*2,r*2);


repaint();

Rectangle bounds=getBounds();

if((x-r+dx<0) || (x+r+dx > bounds.width))

dx=-dx;


if((y-r+dy<0) || (y+r+dy > bounds.height))

dy=-dy;


x+=dx;

y+=dy;

try

{

Thread.sleep(10);

}

catch(InterruptedException e)

{

}

}

};

f.add(p);

f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);

f.setSize(300,300);

f.setVisible(true);

}

public static void main(String args[])

{

new BC();

}

}