Friday, March 7, 2008

MessageLabel autoreset JLabel after few seconds.


This demo show the usage of Timer class of swing package. It will hide the label after few seconds when we use the setText() method.

Generally this program used for Conformation or Error Message.


/**
 * Class used to show the Confirmation label of Error label for predefined duration.
 * After duration it will auto hide using
 * @code setVisible(false);
 *
 * Usage :
 *
 * Create object of MessageLabel using
 * MessageLabel labelConformation = new MessageLable(false);
 * labelConformation.setText("This is Demo from Shirin and Khushal");
 *
 * And add that to your panel and enjoy the effect.
 *
 */

import java.awt.Color;
import javax.swing.JLabel;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.Timer;

/**
 * 
 * @author Shirin, Khushal
 */
public class MessageLabel extends JLabel {

 int count = 0;

 Timer timer;

 int duration = 2000; // default duration in milliSeconds 1000 i.e. 1
       // Second

 /**
  * Listner will call at given duration..
  */
 ActionListener listener = new ActionListener() {
  public void actionPerformed(ActionEvent e) {
   count++;
   System.out.println(count);
   /*
    * Check for count if equls to seconds than will remove the listener
    * and stop the counter and hide the label.
    */

   if (count >= duration / 1000) {
    setVisible(false);
    try {
     timer.stop();
     timer.removeActionListener(listener);
     count = 0;
    } catch (Exception ex) {
     ex.printStackTrace();
    }
   }
  }
 };

 /**
  * method will set if error message than color of label will red else blue.
  * 
  * @param p_isErrorMessage
  */
 public MessageLabel(boolean p_isErrorMessage) {
  super();
  timer = new Timer(duration, listener);
  if (p_isErrorMessage) {
   setForeground(Color.red);
  } else {
   setForeground(Color.blue);
  }
 }

 /**
  * Override method which will invoke timer after every duration .. and will
  * display the label and hide too.
  * 
  * @param text
  */

 @Override
 public void setText(String text) {
  setVisible(true);
  super.setText(text);
  setSize(getPreferredSize());
  // timer.addActionListener(listener);
  if (timer != null) {
   timer.addActionListener(listener);
   timer.start();
  }
 }

 /**
  * method will set the duration value...
  * 
  * @param p_duration
  */

 public void setDuration(int p_duration) {
  duration = p_duration;
 }

}

No comments:

Contributors