Crenox

Bouncing a ball in Java

May 10th, 2013
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.03 KB | None | 0 0
  1. Link:
  2. http://www.ntu.edu.sg/home/ehchua/programming/java/J8a_GameIntro-BouncingBalls.html
  3. Code:
  4. import java.awt.*;
  5. import java.util.Formatter;
  6. import javax.swing.*;
  7. /**
  8. * One ball bouncing inside a rectangular box.
  9. * All codes in one file. Poor design!
  10. */
  11. // Extends JPanel, so as to override the paintComponent() for custom rendering codes.
  12. public class BouncingBallSimple extends JPanel {
  13. // Container box's width and height
  14. private static final int BOX_WIDTH = 640;
  15. private static final int BOX_HEIGHT = 480;
  16.  
  17. // Ball's properties
  18. private float ballRadius = 200; // Ball's radius
  19. private float ballX = ballRadius + 50; // Ball's center (x, y)
  20. private float ballY = ballRadius + 20;
  21. private float ballSpeedX = 3; // Ball's speed for x and y
  22. private float ballSpeedY = 2;
  23.  
  24. private static final int UPDATE_RATE = 30; // Number of refresh per second
  25.  
  26. /** Constructor to create the UI components and init game objects. */
  27. public BouncingBallSimple() {
  28. this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
  29.  
  30. // Start the ball bouncing (in its own thread)
  31. Thread gameThread = new Thread() {
  32. public void run() {
  33. while (true) { // Execute one update step
  34. // Calculate the ball's new position
  35. ballX += ballSpeedX;
  36. ballY += ballSpeedY;
  37. // Check if the ball moves over the bounds
  38. // If so, adjust the position and speed.
  39. if (ballX - ballRadius < 0) {
  40. ballSpeedX = -ballSpeedX; // Reflect along normal
  41. ballX = ballRadius; // Re-position the ball at the edge
  42. } else if (ballX + ballRadius > BOX_WIDTH) {
  43. ballSpeedX = -ballSpeedX;
  44. ballX = BOX_WIDTH - ballRadius;
  45. }
  46. // May cross both x and y bounds
  47. if (ballY - ballRadius < 0) {
  48. ballSpeedY = -ballSpeedY;
  49. ballY = ballRadius;
  50. } else if (ballY + ballRadius > BOX_HEIGHT) {
  51. ballSpeedY = -ballSpeedY;
  52. ballY = BOX_HEIGHT - ballRadius;
  53. }
  54. // Refresh the display
  55. repaint(); // Callback paintComponent()
  56. // Delay for timing control and give other threads a chance
  57. try {
  58. Thread.sleep(1000 / UPDATE_RATE); // milliseconds
  59. } catch (InterruptedException ex) { }
  60. }
  61. }
  62. };
  63. gameThread.start(); // Callback run()
  64. }
  65.  
  66. /** Custom rendering codes for drawing the JPanel */
  67. @Override
  68. public void paintComponent(Graphics g) {
  69. super.paintComponent(g); // Paint background
  70.  
  71. // Draw the box
  72. g.setColor(Color.BLACK);
  73. g.fillRect(0, 0, BOX_WIDTH, BOX_HEIGHT);
  74.  
  75. // Draw the ball
  76. g.setColor(Color.BLUE);
  77. g.fillOval((int) (ballX - ballRadius), (int) (ballY - ballRadius),
  78. (int)(2 * ballRadius), (int)(2 * ballRadius));
  79.  
  80. // Display the ball's information
  81. g.setColor(Color.WHITE);
  82. g.setFont(new Font("Courier New", Font.PLAIN, 12));
  83. StringBuilder sb = new StringBuilder();
  84. Formatter formatter = new Formatter(sb);
  85. formatter.format("Ball @(%3.0f,%3.0f) Speed=(%2.0f,%2.0f)", ballX, ballY,
  86. ballSpeedX, ballSpeedY);
  87. g.drawString(sb.toString(), 20, 30);
  88. }
  89.  
  90. /** main program (entry point) */
  91. public static void main(String[] args) {
  92. // Run GUI in the Event Dispatcher Thread (EDT) instead of main thread.
  93. javax.swing.SwingUtilities.invokeLater(new Runnable() {
  94. public void run() {
  95. // Set up main window (using Swing's Jframe)
  96. JFrame frame = new JFrame("A Bouncing Ball");
  97. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  98. frame.setContentPane(new BouncingBallSimple());
  99. frame.pack();
  100. frame.setVisible(true);
  101. }
  102. });
  103. }
  104. }
Advertisement
Add Comment
Please, Sign In to add comment