How to Animate a JPanel in Java


The Swing software library of the Java language components includes a set of programming controls to design visual interface of your Java programs. It includes tools for creating and editing graphic elements and interactive features in the user application, such as animation of the application panels. You use the timer and action listener properties of the JPanel program module to turn on the animation function. By animating a JPanel elements in the Java program, you can add visual effects to your applications.

  • Click "Start" in Windows, and then click "Java Swing JFC."

  • Click "File," select "Open" and then double-click on the Java program in which you want to add animation of the JPanel.

  • Add the following code after "public class" line:

    //... Instance variables for the animation

    private int m_interval = 35; // Milliseconds between


    private Timer m_timer;           // Timer fires to animate 

    one step.


    /** Set panel size and creates timer. */

    public Box() {

    setPreferredSize(new Dimension(200, 80));


    m_timer = new Timer(m_interval, new TimerAction());



    /** Turn animation on or off.

    *@param turnOnOff Specifies state of animation.


    public void setAnimation(boolean turnOnOff) {

    if (turnOnOff) {

    m_timer.start(); // start animation by starting the


        } else {

    m_timer.stop(); // stop timer



  • Click "File," and then click "Save" to turn on the animation of JPanel in your Java program.

Related Searches


  • Photo Credit Chad Baker/Photodisc/Getty Images
Promoted By Zergnet


You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!