1 30 package com.genimen.djeneric.ui; 31 32 import java.awt.Dimension ; 33 import java.awt.FontMetrics ; 34 import java.awt.Graphics ; 35 import java.io.BufferedReader ; 36 import java.io.IOException ; 37 import java.io.StringReader ; 38 import java.util.Enumeration ; 39 import java.util.Vector ; 40 41 import javax.swing.JComponent ; 42 import javax.swing.JLabel ; 43 import javax.swing.JToolTip ; 44 import javax.swing.SwingUtilities ; 45 import javax.swing.plaf.metal.MetalToolTipUI ; 46 47 import com.genimen.djeneric.util.DjLogger; 48 49 public class DjMultiLineToolTip extends JToolTip 50 { 51 private static final long serialVersionUID = 1L; 52 53 public DjMultiLineToolTip() 54 { 55 setUI(new MultiLineToolTipUI()); 56 } 57 } 58 59 class MultiLineToolTipUI extends MetalToolTipUI 60 { 61 private String [] strs; 62 63 public void paint(Graphics g, JComponent c) 64 { 65 FontMetrics metrics = new JLabel ().getFontMetrics(c.getFont()); 66 Dimension size = c.getSize(); 67 g.setColor(c.getBackground()); 68 g.fillRect(0, 0, size.width, size.height); 69 g.setColor(c.getForeground()); 70 if (strs != null) 71 { 72 for (int i = 0; i < strs.length; i++) 73 { 74 g.drawString(strs[i], 3, (metrics.getHeight()) * (i + 1)); 75 } 76 } 77 } 78 79 public Dimension getPreferredSize(JComponent c) 80 { 81 FontMetrics metrics = new JLabel ().getFontMetrics(c.getFont()); 82 String tipText = ((JToolTip ) c).getTipText(); 83 if (tipText == null) 84 { 85 tipText = ""; 86 } 87 BufferedReader br = new BufferedReader (new StringReader (tipText)); 88 String line; 89 int maxWidth = 0; 90 Vector v = new Vector (); 91 try 92 { 93 while ((line = br.readLine()) != null) 94 { 95 int width = SwingUtilities.computeStringWidth(metrics, line); 96 maxWidth = (maxWidth < width) ? width : maxWidth; 97 v.addElement(line); 98 } 99 } 100 catch (IOException ex) 101 { 102 DjLogger.log(ex); 103 } 104 int lines = v.size(); 105 if (lines < 1) 106 { 107 strs = null; 108 lines = 1; 109 } 110 else 111 { 112 strs = new String [lines]; 113 int i = 0; 114 for (Enumeration e = v.elements(); e.hasMoreElements(); i++) 115 { 116 strs[i] = (String ) e.nextElement(); 117 } 118 } 119 int height = metrics.getHeight() * lines; 120 return new Dimension (maxWidth + 6, height + 4); 121 } 122 } | Popular Tags |