How to Create a Bouncing Ball Animation In Java Netbeans
In this Java Tutorial we will see How To Create a basic graphical application where a ball moves within a panel, bouncing off its borders.
The animation is achieved through a timer that updates the ball's position and triggers the repainting of the panel at regular intervals.
What We Are Gonna Use In This Project:
- Java Programming Language.- NetBeans Editor.
Project Source Code:
package new_tutorials;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
*
* @author 1BestCsharp
*/
public class BouncingBall extends JPanel {
private int ballX = 50; // Initial X coordinate of the ball
private int ballY = 50; // Initial Y coordinate of the ball
private int ballSpeedX = 2; // Speed of the ball in the X direction
private int ballSpeedY = 2; // Speed of the ball in the Y direction
private int ballSize = 100; // Size of the ball
public BouncingBall(){
// Set up a timer to update the game state every 10 milliseconds
Timer timer = new Timer(10, ((e) -> {
updatePanelState();
repaint();
}));
timer.start();
}
private void updatePanelState()
{
// Update the position of the ball
ballX += ballSpeedX;
ballY += ballSpeedY;
// Check if the ball hits the borders of the panel
if(ballX <= 0 || ballX >= getWidth() - ballSize)
{
ballSpeedX *= -1; // Reverse the X direction
}
if(ballY <= 0 || ballY >= getHeight() - ballSize)
{
ballSpeedY *= -1; // Reverse the Y direction
}
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// Draw the ball
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.ORANGE);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(ballX, ballY, ballSize, ballSize);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bouncing Ball");
BouncingBall panel = new BouncingBall();
panel.setBackground(Color.BLACK);
frame.add(panel);
frame.setSize(800,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The Final Result:
More Java Projects:
Download Projects Source Code