0% found this document useful (0 votes)
13 views

Bouncing Ball PDF

The document describes a Java program that simulates a bouncing ball. The program uses a thread to continuously update the ball's position as it bounces around the screen boundaries. The ball's position, size, and direction of movement are defined. The program draws the ball and animates its movement.

Uploaded by

Ikrash official
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Bouncing Ball PDF

The document describes a Java program that simulates a bouncing ball. The program uses a thread to continuously update the ball's position as it bounces around the screen boundaries. The ball's position, size, and direction of movement are defined. The program draws the ball and animates its movement.

Uploaded by

Ikrash official
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Islamia college Peshawar

Assignment of java (oop)


3rd assaigment
Prepared by Muhammad Irfan
Submitted to: Dr Irshad Ahmad
Name : Muhammad Irfan
Class :software engineering
Bouncing ball:
Picture:
Source code :
import java.awt.*;
import javax.swing.*;

public class BouncingBall extends JPanel {

// Box height and width


int wi;
int he;

// Ball Size
float radius = 20;
float diameter = radius * 2;

// Center of Call
float X = radius + 50;
float Y = radius + 20;

// Direction
float dx = 3;
float dy = 3;

public BouncingBall() {

Thread thread = new Thread() {


public void run() {
while (true) {

wi = getWidth();
he= getHeight();

X = X + dx ;
Y = Y + dy;

if (X - radius < 0) {
dx = -dx;
X = radius;
} else if (X + radius > wi) {
dx = -dx;
X = wi - radius;
}

if (Y - radius < 0) {
dy = -dy;
Y = radius;
} else if (Y + radius > he) {
dy = -dy;
Y = he - radius;
}
repaint();

try {
Thread.sleep(50);
} catch (InterruptedException ex) {
}

}
}
};
thread.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.fillOval((int)(X-radius), (int)(Y-radius), (int)diameter,
(int)diameter);
}

public static void main(String[] args) {


JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Bouncing Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setContentPane(new BouncingBall());
frame.setVisible(true);
}
}

You might also like