Java Source Code For Simple Animation Making With Swing

If you are a newbie for learning to use Java Swing and wanna to make a simple animation. Then this post is for you. Here I will give you a source for simple animation making with the swing by Java Codes. using these codes you will able to make an animation, that makes a small shape bounce around the predetermined borders of a panel.
Read Also:
1. Games With HTML Codes: Make A Snake Game With Notepad
2. How To Make IP Finder In Java With Source Code
3. Make Clock and Date Using Notepad Text Editor
4. How Do You Make A Game Using Notepad

Code For Simple Animation Making With Swing

The codes appear below;

import javax.swing.*;
import java.awt.*;

final public class Tester {

    JFrame frame;
    DrawPanel drawPanel;

    private int oneX = 7;
    private int oneY = 7;

    boolean up = false;
    boolean down = true;
    boolean left = false;
    boolean right = true;

    public static void main(String[] args) {
        new Tester().go();
    }

    private void go() {
        frame = new JFrame(“Test”);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        drawPanel = new DrawPanel();

        frame.getContentPane().add(BorderLayout.CENTER, drawPanel);

        frame.setVisible(true);
        frame.setResizable(false);
        frame.setSize(300, 300);
        frame.setLocation(375, 55);
        moveIt();
    }

    class DrawPanel extends JPanel {
        public void paintComponent(Graphics g) {
            g.setColor(Color.BLUE);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            g.setColor(Color.RED);
            g.fillRect(3, 3, this.getWidth()-6, this.getHeight()-6);
            g.setColor(Color.WHITE);
            g.fillRect(6, 6, this.getWidth()-12, this.getHeight()-12);
            g.setColor(Color.BLACK);
            g.fillRect(oneX, oneY, 6, 6);
        }
    }

    private void moveIt() {
        while(true){
            if(oneX >= 283){
                right = false;
                left = true;
            }
            if(oneX <= 7){
                right = true;
                left = false;
            }
            if(oneY >= 259){
                up = true;
                down = false;
            }
            if(oneY <= 7){
                up = false;
                down = true;
            }
            if(up){
                oneY–;
            }
            if(down){
                oneY++;
            }
            if(left){
                oneX–;
            }
            if(right){
                oneX++;
            }
            try{
                Thread.sleep(10);
            } catch (Exception exc){}
            frame.repaint();
        }
    }
}

Just copy these code and make your first simple animation in Java with Swing. Have any question or problem? Ask me via the comment section. I will try to solve it as soon as possible. If it’s helpful then share it in social media with your buddies.

Leave a Comment