Wednesday, June 25, 2025

[JAVA] ANIMATION

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

class MovingObject {
    int x, y, width, height;
    Color color;

    public MovingObject(int x, int y, int width, int height, Color color) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.color = color;
    }

    public void move(int dx, int dy) {
        x += dx;
        y += dy;
    }

    public void draw(Graphics g) {
        g.setColor(color);
        g.fillRect(x, y, width, height);
    }
}

public class AnimationDemo extends JPanel implements ActionListener {
    private List<MovingObject> objects;
    private Timer timer;

    public AnimationDemo() {
        objects = new ArrayList<>();
        objects.add(new MovingObject(50, 50, 50, 50, Color.RED));
        objects.add(new MovingObject(150, 100, 50, 50, Color.BLUE));
        objects.add(new MovingObject(250, 150, 50, 50, Color.GREEN));

        timer = new Timer(30, this);
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0, 0, getWidth(), getHeight());

        for (MovingObject obj : objects) {
            obj.draw(g);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        for (MovingObject obj : objects) {
            obj.move(1, 1);
            if (obj.x > getWidth()) obj.x = 0;
            if (obj.y > getHeight()) obj.y = 0;
        }
        repaint();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("2D Animation");
        AnimationDemo animation = new AnimationDemo();
        frame.add(animation);
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

No comments: