示例代码如下: public class LineNumberHeaderView extends javax.swing.JComponent { private final Font DEFAULT_FONT = new Font(Font.MONOSPACED, Font.PLAIN, 13); public final Color DEFAULT_BACKGROUD = new Color(228, 228, 228); public final Color DEFAULT_FOREGROUD = Color.red; public final int nHEIGHT = Integer.MAX_VALUE - 1000000; public final int MARGIN = 5; private int lineHeight; private int fontLineHeight; private int currentRowWidth; private FontMetrics fontMetrics; public LineNumberHeaderView() { setFont(DEFAULT_FONT); setForeground(DEFAULT_FOREGROUD); setBackground(DEFAULT_BACKGROUD); setPreferredSize(9999); } public void setPreferredSize(int row) { int width = fontMetrics.stringWidth(String.valueOf(row)); if (currentRowWidth < width) { currentRowWidth = width; setPreferredSize(new Dimension(2 * MARGIN + width + 1, nHEIGHT)); } } @Override public void setFont(Font font) { super.setFont(font); fontMetrics = getFontMetrics(getFont()); fontLineHeight = fontMetrics.getHeight(); } public int getLineHeight() { if (lineHeight == 0) { return fontLineHeight; } return lineHeight; } public void setLineHeight(int lineHeight) { if (lineHeight > 0) { this.lineHeight = lineHeight; } } public int getStartOffset() { return 4; } @Override protected void paintComponent(Graphics g) { int nlineHeight = getLineHeight(); int startOffset = getStartOffset(); Rectangle drawHere = g.getClipBounds(); g.setColor(getBackground()); g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height); g.setColor(getForeground()); int startLineNum = (drawHere.y / nlineHeight) + 1; int endLineNum = startLineNum + (drawHere.height / nlineHeight); int start = (drawHere.y / nlineHeight) * nlineHeight + nlineHeight - startOffset; for (int i = startLineNum; i <= endLineNum; ++i) { String lineNum = String.valueOf(i); int width = fontMetrics.stringWidth(lineNum); g.drawString(lineNum + " ", MARGIN + currentRowWidth - width - 1, start); start += nlineHeight; } setPreferredSize(endLineNum); } public static void main(String[] args){ // try { // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // } catch (Exception e) { // e.printStackTrace(); // } JFrame frame = new JFrame("带行号的TextArea Demo"); JLabel label = new JLabel(" 编辑区域"); LineNumberHeaderView view = new LineNumberHeaderView(); JScrollPane scrollPane = new JScrollPane(new JTextArea()); scrollPane.setRowHeaderView(view); frame.getContentPane().add(label, "North"); frame.getContentPane().add(scrollPane,"Center"); frame.setPreferredSize(new Dimension(300, 200)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(200, 200, 300, 200); frame.setVisible(true); } } 运行效果如下所示: