學(xué)java編程一段時(shí)間了,想利用java swing開(kāi)發(fā)一個(gè)桌面的文本編輯器程序,首先想要實(shí)現(xiàn)的便是顯示行號(hào)的功能,由于要實(shí)現(xiàn)一些關(guān)鍵詞著色功能,選擇了JTextPane,其實(shí)還有一個(gè)JEditorPane也可以設(shè)定顏色屬性的,但JTextPane是繼承JEditorPane的,貌似功能應(yīng)該更強(qiáng)大些。。接下來(lái)就是如何在JTextPane上實(shí)現(xiàn)行號(hào)顯示的功能了,首先第一個(gè)念頭是在一個(gè)JTextPane中實(shí)現(xiàn)實(shí)時(shí)輸入內(nèi)容后計(jì)算行數(shù),每行行號(hào)顯示在行首處,說(shuō)得容易,實(shí)際操作并不如此,因?yàn)槟阋紤]用戶(hù)進(jìn)行刪除單詞等一系列的操作,而且這么做的話(huà)文本框里的內(nèi)容連行號(hào)也包括了,當(dāng)要輸出為一個(gè)文件時(shí)就麻煩了,你還要想辦法去掉那些被當(dāng)做文本內(nèi)容的行號(hào)!還有什么辦法呢?經(jīng)思考最終決定使用兩個(gè)JTextPane,一個(gè)作為文本輸入框,一個(gè)作為行號(hào)欄,大體如下,使用一個(gè)JFrame,JFrame使用BorderLayout布局,行號(hào)欄布局在BorderLayout.WEST,文本輸入框布局在CENTER,這樣就ok了,其中有一個(gè)發(fā)現(xiàn)要注意的是,要想行號(hào)欄上的行號(hào)與右邊文本框的每一行內(nèi)容對(duì)齊,得用一樣的字體顏色屬性.....
以下分享一些代碼用于常見(jiàn)的獲取文本行數(shù)等屬性...
public class DocAttribute{ //返回光標(biāo)所在列 public static int getColumnAtCaret(JTextComponent component) { int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); int line = root.getElementIndex( caretPosition ); int lineStart = root.getElement( line ).getStartOffset(); return caretPosition - lineStart + 1; } //獲取指定行的第一個(gè)字符位置 public static int getLineStart(JTextComponent component,int line) { int lineNumber = line - 1; Element root = component.getDocument().getDefaultRootElement(); int lineStart = root.getElement( lineNumber ).getStartOffset(); return lineStart; } //返回選中的字符數(shù) public static int getSelectedNumber(JTextComponent component) { if( component.getSelectedText() == null ) return 0; else return component.getSelectedText().length(); } //返回光標(biāo)所在行 public static int getLineAtCaret(JTextComponent component) { int caretPosition = component.getCaretPosition(); Element root = component.getDocument().getDefaultRootElement(); return root.getElementIndex( caretPosition ) + 1; } //返回文本行數(shù) public static int getLines(JTextComponent component) { Element root = component.getDocument().getDefaultRootElement(); return root.getElementCount(); } //返回文本框的字符總數(shù) public static int getCharNumber(JTextComponent component) { Document doc = component.getDocument(); return doc.getLength(); }新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注