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();方法就可以了。

版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值