1 20 package edu.umd.cs.findbugs.gui; 21 22 import java.awt.Color ; 23 import java.awt.Dimension ; 24 import java.awt.Font ; 25 import java.awt.FontMetrics ; 26 import java.awt.Graphics ; 27 import java.awt.Rectangle ; 28 29 import javax.swing.JComponent ; 30 import javax.swing.JTextArea ; 31 32 public class LineNumberer extends JComponent 33 { 34 public static final int PAD = 10; 35 public static final String PROTOTYPE = "00000"; 36 37 private JTextArea textArea; 38 private FontMetrics fm; 39 40 public LineNumberer(JTextArea ta) { 41 setFont( ta.getFont() ); 42 textArea = ta; 43 setForeground( Color.BLUE ); 44 45 fm = this.getFontMetrics(ta.getFont()); 46 setWidths(); 47 } 48 49 @Override 50 public void setFont(Font font) 51 { 52 } 54 55 private void setWidths() { 56 int width = fm.stringWidth( PROTOTYPE ); 57 Dimension d = getPreferredSize(); 58 d.setSize(PAD + width, Integer.MAX_VALUE); 59 setPreferredSize( d ); 60 setSize( d ); 61 } 62 63 64 @Override 65 public void paintComponent(Graphics g) 66 { 67 int lineHeight = fm.getHeight(); 68 int startOffset = textArea.getInsets().top + fm.getAscent(); 69 70 Rectangle clip = g.getClipBounds(); 71 72 g.setColor( getBackground() ); 73 g.fillRect(clip.x, clip.y, clip.width, clip.height); 74 75 g.setColor( getForeground() ); 76 int beginLineNumber = (clip.y / lineHeight) + 1; 77 int endLineNumber = beginLineNumber + (clip.height / lineHeight); 78 79 int y = (clip.y / lineHeight) * lineHeight + startOffset; 80 81 for (int i = beginLineNumber; i <= endLineNumber; i++) 82 { 83 String ln = String.valueOf(i); 84 int width = fm.stringWidth( ln ); 85 int rowWidth = getSize().width; 86 g.drawString(ln, rowWidth - width - PAD, y); 87 y += lineHeight; 88 } 89 } 90 } 91 | Popular Tags |