How to create marquee JLabel in Java



I Just given code for Marquee JLable.

 import java.awt.Graphics;  
 import javax.swing.JLabel;  
 public class MarqueeLabel extends JLabel {  
   public static int LEFT_TO_RIGHT = 1;  
   public static int RIGHT_TO_LEFT = 2;  
   String text;  
   int Option;  
   int Speed;  
   public MarqueeLabel(String text, int Option, int Speed) {  
     this.Option = Option;  
     this.Speed = Speed;  
     this.setText(text);  
   }  
   @Override  
   protected void paintComponent(Graphics g) {  
     if (Option == LEFT_TO_RIGHT) {  
       g.translate((int) ((System.currentTimeMillis() / Speed) % (getWidth() * 2) - getWidth()), 0);  
     } else if (Option == RIGHT_TO_LEFT) {  
       g.translate((int) (getWidth() - (System.currentTimeMillis() / Speed) % (getWidth() * 2)), 0);  
     }  
     super.paintComponent(g);  
     repaint(5);  
   }  
 }  

How to Use

 MarqueeLabel myLable = new MarqueeLabel("Welcome to www.How2Java.com", MarqueeLabel.RIGHT_TO_LEFT, 20);  

or

 JLabel myLable = new MarqueeLabel("Welcome to www.How2Java.com", MarqueeLabel.RIGHT_TO_LEFT, 20);  




 Parameters :

1. Text  :  Text set to JLable
2. Direction :  There is two constant  MarqueeLabel.RIGHT_TO_LEFT and MarqueeLabel.LEFT_TO_RIGHT
3. Speed  :  int value (increasing value then decreasing speed and decreasing value then increasing speed)


No comments:

Post a Comment