import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

/**
 * 
 * ToolTip: Heavy Weight ToolTip
 *
 * @version     1.0
 * @author :    Kovalan Muniandy
 *
 */

public class ToolTip extends JPopupMenu implements Runnable {
    protected final int MAX_TEXT = 45;
    final Font prefferedFont = new Font( "Arial",Font.PLAIN, 10 );
    protected int timer = 4000;
    public ToolTip( String theText ) {
        super();
        Vector text = new Vector();
        text.add( theText );
        init( text, -1 );
    }
    public ToolTip( String theText, int theTimer ) {
        super();
        Vector text = new Vector();
        text.add( theText );
        init( text, -1 );
    }
    public ToolTip( Vector texts ) {
        super();
        init( texts, -1 );
    }
    protected void init( Vector texts, int theTimer ) {
        if ( theTimer != -1 )
            timer = theTimer;
        setDefaultLightWeightPopupEnabled( false );            
        for ( int i=0; i < texts.size(); i++ ) {
            String theText = (String)texts.get(i);
            add( new ToolTipItem( theText ) );
        }
        setFont( prefferedFont );
        Thread closer = new Thread( this );
        closer.start();
    }
    public void run() {
        try {
            Thread.sleep( timer );
            setVisible( false );
            setEnabled( false );
        }
        catch( InterruptedException e ) {
        }
    }
    public void paint( Graphics g ) {
        setBackground( Color.white );
        super.paint( g );
        Rectangle rect = getBounds();
        g.setColor( Color.black );
        g.drawRect( 0, 0, rect.width-1, rect.height-1 );
    }
    public Point getCenteredTextLoc( Graphics g, String text, Rectangle bounds ) {
        FontMetrics metrics = g.getFontMetrics();
            
        int width = metrics.charsWidth( 
                        text.toCharArray(), 0, text.length() );
        int height = metrics.charsWidth( 
                        text.toCharArray(), 0, text.length() );

        if ( width >= (int)bounds.getWidth() ) {
            text = text.substring(0, MAX_TEXT);
            text += "...";
            width = metrics.charsWidth( 
                text.toCharArray(), 0, text.length() );
        }
                
        return new Point( (int)((bounds.getWidth() - width)/2.0),
                            (int)((bounds.getHeight() - height)/2.0));
    }
    protected class ToolTipItem extends JMenuItem {
        public ToolTipItem( String theText ) {
            super( theText );
            setFont( prefferedFont );
        }
            
        public void paint( Graphics g ) {
            setBackground( Color.white );
            setArmed( false );
            super.paint( g );
        }
    }
}
