最近項目需求,需要在jtextpane上添加行号等資訊,網上找了好久隻找到jtextarea添加行号資訊,copy網上的程式研究了下,發現自己改改就可以讓jtextpane顯示行号!
代碼:
package com.cml.line;
import java.awt.color;
import java.awt.fontmetrics;
import java.awt.component;
import java.awt.graphics;
import java.awt.insets;
import javax.swing.jtextarea;
import javax.swing.jtextpane;
import javax.swing.border.abstractborder;
public class linenumberborder extends abstractborder
{
public linenumberborder()
}
/*
* insets 對象是容器邊界的表示形式。 它指定容器必須在其各個邊緣留出的空間。
*/
// 此方法在執行個體化時自動調用
// 此方法關系到邊框是否占用元件的空間
public insets getborderinsets(component c)
return getborderinsets(c, new insets(0, 0, 0, 0));
public insets getborderinsets(component c, insets insets)
if (c instanceof jtextpane)
//這裡設定行号左邊邊距
insets.left = 20;
}
return insets;
public boolean isborderopaque()
return false;
// 邊框的繪制方法
// 此方法必須實作
public void paintborder(component c, graphics g, int x, int y, int width,
int height)
// 獲得目前剪貼區域的邊界矩形。
java.awt.rectangle clip = g.getclipbounds();
fontmetrics fm = g.getfontmetrics();
int fontheight = fm.getheight();
// starting location at the "top" of the page...
// y is the starting baseline for the font...
int ybaseline = y + fm.getascent();
// now determine if it is the "top" of the page...or somewhere
// else
int startinglinenumber = (clip.y / fontheight) + 1;
if (startinglinenumber != 1)
ybaseline = y + startinglinenumber * fontheight
- (fontheight - fm.getascent());
int yend = ybaseline + height;
if (yend > (y + height))
yend = y + height;
g.setcolor(color.blue);
// 繪制行号
while (ybaseline < yend)
string label = padlabel(startinglinenumber, 0, true);
g.drawstring(label, 0, ybaseline);
ybaseline += fontheight;
startinglinenumber++;
// 尋找适合的數字寬度
private int linenumberwidth(jtextarea jta)
int linecount = math.max(jta.getrows(), jta.getlinecount());
return jta.getfontmetrics(jta.getfont()).stringwidth(linecount + " ");
private string padlabel(int linenumber, int length, boolean addspace)
stringbuffer buffer = new stringbuffer();
buffer.append(linenumber);
for (int count = (length - buffer.length()); count > 0; count--)
buffer.insert(0, ‘ ‘);
if (addspace)
buffer.append(‘ ‘);
return buffer.tostring();
源代碼是網上下的,下了好久了,忘了是誰的了。
使用時隻需喲調用jtextpane的setborder();方法就可以了!