Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.imageio.ImageIO;
- import javax.swing.*;
- import java.awt.*;
- import java.io.IOException;
- import java.util.Random;
- class Moon {
- Image picture;
- int x;
- int y;
- Moon(int x, int y) throws IOException {
- this.x = x;
- this.y = y;
- picture = ImageIO.read(new java.io.File("moon.jpg"));
- }
- void shine(Graphics g) {
- g.drawImage(picture, x, y, 100, 100, null);
- }
- }
- class Ball {
- double x, y;
- double v;
- Ball(int x, int y) {
- this.x = x;
- this.y = y;
- v = 3;
- }
- void updateCoordinates(Rectangle rect) {
- final double g = 0.25;
- v += g;
- if (y + 45 > rect.height) {
- v *= -1;
- }
- y += v;
- }
- void draw(Graphics g) {
- g.setColor(new Color(200, 100, 100));
- g.fillOval((int) this.x, (int) this.y, 60, 60);
- }
- }
- class Panel extends JPanel {
- Ball[] balls;
- Moon moon;
- Panel() throws IOException {
- Timer nt = new Timer(10, e -> repaint());
- nt.start();
- Random random = new Random(42);
- moon = new Moon(50, 50);
- balls = new Ball[10];
- for (int i = 0; i < balls.length; ++i) {
- balls[i] = new Ball(random.nextInt(750), random.nextInt(400));
- }
- }
- public void paintComponent(Graphics g) {
- Rectangle canvas = g.getClipBounds();
- g.clearRect(0, 0, canvas.width, canvas.height);
- moon.shine(g);
- for (Ball ball : balls) {
- ball.updateCoordinates(canvas);
- ball.draw(g);
- }
- }
- }
- class Frame extends JFrame {
- Frame(int width, int height) throws IOException {
- Panel panel = new Panel();
- Container container = getContentPane();
- container.add(panel);
- setSize(width, height);
- setVisible(true);
- setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- }
- }
- public class Main {
- public static void main(String[] args) throws IOException {
- new Frame(800, 600);
- }
- }
Add Comment
Please, Sign In to add comment