Slide JLabel in JFrame: Creating a slick effect

Here is how to slide JLabel in JFrame to create an animated slick effect. The program consists of a simple JLabel with an ImageIcon that slides about x-axis from one side to the center. Here is the program.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.image.*;
class AnimateJLabel extends JFrame
JLabel l;
ImageIcon icon;
Timer t;
int x=0;

public AnimateJLabel()

private void createAndShowGUI()
// Set frame properties
setTitle("Animate JLabel");
setLayout(new GridBagLayout());

// Create an ImageIcon
icon=new ImageIcon("D:\\Documents and Settings\\Gutha\\My Documents\\Downloads\\cloud_icon.png");

// Create a JLabel
l=new JLabel("");

// Set the text position bottom center relative
// to the icon so that the icon appears as a
// a desktop icon

// Set the icon to the JLabel

// Set some font
l.setFont(new Font("Myriad Pro",Font.PLAIN,28));

// Initially, the label isn't visible

// Add the JLabel

// Create a Timer with that executes
// each 1ms
t=new Timer(1,new ActionListener(){

public void actionPerformed(ActionEvent ae)
// First time, make the JLabel visible
// You don't need to call this again because
// the label is visible when this is first
// executed. Calling it every time the timer fires
// is redundant
if(x==0) l.setVisible(true);

// Set the location, only the x-co ordinate gets
// updated (incremented by 1 each time) and the y remains
// constant here because getHeight() and l.getHeight() both
// are constant

// If x equals half of the width of the JFrame
// i.e. reaches center, then stop the timer
if(x==getWidth()/2) t.stop();

// Set some initial delay, optional

// Start the timer

// Set size and show the frame

public static void main(String args[])
SwingUtilities.invokeLater(new Runnable(){
public void run()
new AnimateJLabel();

If you like this post, you might also like to see fade effect for JLabel and also animating JFrame with random colors and create a moving JFrame in swing

Posted by at on

Tags: Swing Animation,