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

Java Bouncing Ball Activity

This Java program simulates a bouncing ball by creating a Ball class that extends JPanel. It uses a Timer to repeatedly move the ball left/right and up/down within the frame boundaries at a fixed rate, repainting after each move. The ball is drawn as a filled oval using Graphics2D with anti-aliasing enabled. The main method creates a Ball instance, adds it to the frame, and makes the frame visible.

Uploaded by

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

Java Bouncing Ball Activity

This Java program simulates a bouncing ball by creating a Ball class that extends JPanel. It uses a Timer to repeatedly move the ball left/right and up/down within the frame boundaries at a fixed rate, repainting after each move. The ball is drawn as a filled oval using Graphics2D with anti-aliasing enabled. The main method creates a Ball instance, adds it to the frame, and makes the frame visible.

Uploaded by

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

Java Bouncing Ball activity: File name Ball

package ball;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class Ball extends JPanel

int x = 200, y = 250;


int width = 50, height = 50;
int dx = 1, dy = 1;
java.util.Timer move;
static JFrame frame;

Ball(){

frame = new JFrame("Ball Bounce!");


frame.setSize(400,400);
frame.setVisible(true);

setForeground(Color.red);
move = new java.util.Timer();
move.scheduleAtFixedRate(new TimerTask()
{

public void run()

if(x<0)
dx=1;
if(x>=getWidth()-45)
dx=-1;
if(y<0)
dy=1;
if(y>=getHeight()-45)
dy=-1;
x+=dx;
y+=dy;
repaint();
}
},0,5
);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;

g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x,y,width,height);
}
public static void main(String[] args)
{
Ball ball = new Ball();
frame.add(ball);
}
}

You might also like