Guest User

Untitled

a guest
Nov 20th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import javax.imageio.ImageIO;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.io.IOException;
  5. import java.util.Random;
  6.  
  7.  
  8. class Moon {
  9. Image picture;
  10. int x;
  11. int y;
  12.  
  13. Moon(int x, int y) throws IOException {
  14. this.x = x;
  15. this.y = y;
  16. picture = ImageIO.read(new java.io.File("moon.jpg"));
  17. }
  18.  
  19. void shine(Graphics g) {
  20. g.drawImage(picture, x, y, 100, 100, null);
  21. }
  22. }
  23.  
  24.  
  25. class Ball {
  26. double x, y;
  27. double v;
  28.  
  29. Ball(int x, int y) {
  30. this.x = x;
  31. this.y = y;
  32. v = 3;
  33. }
  34.  
  35. void updateCoordinates(Rectangle rect) {
  36. final double g = 0.25;
  37.  
  38. v += g;
  39. if (y + 45 > rect.height) {
  40. v *= -1;
  41. }
  42.  
  43. y += v;
  44. }
  45.  
  46. void draw(Graphics g) {
  47. g.setColor(new Color(200, 100, 100));
  48. g.fillOval((int) this.x, (int) this.y, 60, 60);
  49. }
  50. }
  51.  
  52. class Panel extends JPanel {
  53. Ball[] balls;
  54.  
  55. Moon moon;
  56.  
  57. Panel() throws IOException {
  58. Timer nt = new Timer(10, e -> repaint());
  59. nt.start();
  60. Random random = new Random(42);
  61.  
  62. moon = new Moon(50, 50);
  63.  
  64. balls = new Ball[10];
  65. for (int i = 0; i < balls.length; ++i) {
  66. balls[i] = new Ball(random.nextInt(750), random.nextInt(400));
  67. }
  68. }
  69.  
  70.  
  71. public void paintComponent(Graphics g) {
  72. Rectangle canvas = g.getClipBounds();
  73. g.clearRect(0, 0, canvas.width, canvas.height);
  74.  
  75. moon.shine(g);
  76.  
  77. for (Ball ball : balls) {
  78. ball.updateCoordinates(canvas);
  79. ball.draw(g);
  80. }
  81. }
  82. }
  83.  
  84. class Frame extends JFrame {
  85. Frame(int width, int height) throws IOException {
  86. Panel panel = new Panel();
  87. Container container = getContentPane();
  88. container.add(panel);
  89. setSize(width, height);
  90. setVisible(true);
  91. setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  92. }
  93. }
  94.  
  95. public class Main {
  96. public static void main(String[] args) throws IOException {
  97. new Frame(800, 600);
  98. }
  99. }
Add Comment
Please, Sign In to add comment