Create a moving JFrame in Swing

How to move a JFrame?

Now, let's create a JFrame that moves along the screen acting like a screensaver. All we need to do is to make a moving effect, for this we can either use the javax.swing.Timer class or Threading concept . However we use threading here. Just look at it!

Get ready to move!

import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
class AnimatedJFrame extends JFrame implements Runnable
Thread t;
public AnimatedJFrame()

// Set frame properties
setTitle("Animated JFrame");

// Set some shape, i want a circle
setShape(new Ellipse2D.Double(0,0,500,500));

// Set background for the frame's content pane

// Set opacity, don't make it opaque, that's my wish!


// Create a new thread, run() is written in this class (Runnable implemented)
t=new Thread(this);

// Start the thread

public void run()

// Get the width of the screen, so that the frame has to go till end!
int width=Toolkit.getDefaultToolkit().getScreenSize().width;

// Start the loop
for(int i=0;i<=width;i++)

// If i value equals width (i.e. reaches end of screen), start from starting of the screen (i.e. i=0) so looped forever
if(i==width) i=0;

// Set location, x-coordinate changes but y-coordinate is constant

// Get the effect!


}catch(Exception e){}


public static void main(String args[])
new AnimatedJFrame();


Everything explained there, just go through other swing hacks.

Watch it! The example in real!

Posted by at on

Tags: Swing Hacks,