天天看点

JTextpane 添加行号

最近项目需求,需要在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();方法就可以了!