Selasa, 02 September 2025

JAVA - Simple Animation JPanel

 




package simpleswinganimation;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


public class SimpleSwingAnimation {


    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {

            JFrame frame = new JFrame("Swing Animation");

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            frame.setSize(400, 300);


            AnimatedPanel panel = new AnimatedPanel();

            frame.add(panel);


            Timer timer = new Timer(10, new ActionListener() { // 10ms delay

                @Override

                public void actionPerformed(ActionEvent e) {

                    panel.updatePosition();

                    panel.repaint();

                }

            });

            timer.start();


            frame.setVisible(true);

        });

    }


    static class AnimatedPanel extends JPanel {

        private int x = 0;


        @Override

        protected void paintComponent(Graphics g) {

            super.paintComponent(g);

            g.setColor(Color.BLUE);

            g.fillOval(x, 50, 50, 50);

        }


        public void updatePosition() {

            x += 2; // Move 2 pixels per update

            if (x > getWidth()) {

                x = -50; // Reset position

            }

        }

    }

}

Tidak ada komentar: