//http://www.java2s.com/Code/Java/Swing-JFC/MultiLineToolTipExample.htm
package menu;

import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.metal.MetalToolTipUI;


public class MultiLineToolTip extends JToolTip {
    public MultiLineToolTip() {
        setUI(new MultiLineToolTipUI());
        Font ToolTipFont=new Font(Font.DIALOG, Font.PLAIN, 12);
        this.setFont(ToolTipFont);
    }
    
    public MultiLineToolTip(int initialDelay, int dismissDelay) {
        setUI(new MultiLineToolTipUI());
        ToolTipManager.sharedInstance().setInitialDelay(initialDelay);
        ToolTipManager.sharedInstance().setDismissDelay(dismissDelay);
    }
}

class MultiLineToolTipUI extends MetalToolTipUI {
    private String[] strs;
    private int maxWidth = 0;
    public MultiLineToolTipUI(){
    }
    public void paint(Graphics g, JComponent component) {
        FontMetrics metrics = component.getFontMetrics(g.getFont());
        Dimension size = component.getSize();
        g.setColor(component.getBackground());
        g.fillRect(0, 0, size.width, size.height);
        g.setColor(component.getForeground());
        if (strs != null) {
            for (int i = 0; i < strs.length; i++) {
                g.drawString(strs[i], 3, (metrics.getHeight()) * (i + 1));
            }
        }
    }
    
    public Dimension getPreferredSize(JComponent component) {
        FontMetrics metrics = component.getFontMetrics(component.getFont());
        String tipText = ((JToolTip) component).getTipText();
        if (tipText == null) {
            tipText = "";
        }
        BufferedReader br = new BufferedReader(new StringReader(tipText));
        String line;
        int maxWidth = 0;
        Vector v = new Vector();
        try {
            while ((line = br.readLine()) != null) {
                int width = SwingUtilities.computeStringWidth(metrics, line);
                maxWidth = (maxWidth < width) ? width : maxWidth;
                v.addElement(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        int lines = v.size();
        if (lines < 1) {
            strs = null;
            lines = 1;
        } else {
            strs = new String[lines];
            int i = 0;
            for (Enumeration e = v.elements(); e.hasMoreElements(); i++) {
                strs[i] = (String) e.nextElement();
            }
        }
        int height = metrics.getHeight() * lines;
        this.maxWidth = maxWidth;
        return new Dimension(maxWidth + 6, height + 8);
    }
}

