public class EditPanel extends JTextPane {
/**
*
/
private static final long serialVersionUID = 1L;
/*
* 是否实现行号,默认不显示
*/
private int fontSize = 16;//默认为16号字体public EditPanel() {super();this.setEditable(false);}
public void word() {
Document doc =getDocument();
for(int i=0;i<10;i++)
{SimpleAttributeSet attrset = new SimpleAttributeSet();StyleConstants.setFontSize(attrset,getFontSize() );try {doc.insertString(doc.getLength(), "要插入的内容"+i+"\n", attrset);} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}
}
}
@Override
public void paint(Graphics g) {super.paint(g);StyleConstants.setFontSize(getInputAttributes(), fontSize);drawLineNumber(g);
}
protected void drawLineNumber(Graphics g) {//内容位置setMargin(new Insets(0, 40, 0, 0));// 绘制行号的背景色g.setColor(new Color(180, 180, 180));g.fillRect(0, 0, 40, getHeight());// 获得有多少行StyledDocument docu = getStyledDocument();Element element = docu.getDefaultRootElement();int rows = element.getElementCount();// 绘制行号的颜色// System.out.println("y:" + getY());g.setColor(new Color(90, 90, 90));g.setFont(new Font(getFont().getName(), getFont().getStyle(), fontSize));for (int row = 0; row < rows; row++) {g.drawString((row + 1)+"",2, getPositionY(row + 1));}//获取光标所在的文本Document doc =getDocument();// System.out.println( root.getElementIndex(getCaretPosition()));Element para = element.getElement(element.getElementIndex(getCaretPosition()));int start =para. getStartOffset();int end = para.getEndOffset();String result = null;try {result = doc.getText(start, end - start);} catch (BadLocationException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.print("Result : " + result.replace(" ", ""));//改变所在行的颜色//并且隐藏光标}public int getFontSize() {return fontSize;
}
/*** 获得行号中y坐标的位置<br/>* 在计算的过程中,有一个比率值,该比率值是根据getY()的返回值之差决定的。* @param row 第几行* @return 该行的y坐标位置*/
private int getPositionY(int row) {int y = 0;switch (fontSize) {case 16:y = (row * 23) - 6;break;}return y;
}
}
public static void main(String[] args) {
JFrame jf=new JFrame(“行号测试”);
EditPanel panel=new EditPanel();
panel.word();
panel.setPreferredSize(new Dimension(600,400));
jf.add(new JScrollPane(panel));
jf.setPreferredSize(new Dimension(700,500));
jf.setSize(new Dimension(700,500));
jf.setVisible(true);
}