2009-11-08 52 views
2

我正嘗試使用JTextPane創建所見即所得編輯器。如何複製JTextPane中的樣式文本

我使用DefaultEditorKit.CopyAction在編輯器中複製文本。但是這種方法不保留文本的風格。有人能告訴我如何複製JTextPane中的文本並保留樣式嗎?

回答

0

書籍出版商Manning提供免費下載Matthew Robinson和Pavel Vorobiev在http://www.manning.com/robinson2的第一版「Swing」。 (向下滾動頁面尋找鏈接「下載完整的Swing圖書(MS Word 97)」)

第20章講述瞭如何使用JTextPane作爲編輯組件的一部分來開發所見即所得的RTF編輯器。本書的新版本經過修改並描述了所見即所得HTML編輯器的創建,但它不是免費的。 (儘管該鏈接的頁面說的是,新版本的紙質版本似乎不可用,但電子書是,如果你有興趣的話)。

這對我來說是一個很好的資源,當我試圖做類似的事情。

+0

第一版示例「使用純文本沒有任何屬性上執行剪貼板操作」。問題的關鍵是以一種風格的方式來做到這一點。 – 2013-04-25 06:34:04

1

我有一個類,它使用以下代碼將所有文本從StyledDocument中複製到用戶的剪貼板中;它似乎保留了顏色,粗體和下劃線等屬性(沒有用其他方法測試過)。請注意,「this.doc」是一個StyledDocument。

不保證這是最好的方法。

try 
    { 
     Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard(); 
     RTFEditorKit rtfek = new RTFEditorKit(); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     rtfek.write(baos, this.doc, 0, this.doc.getLength()); 
     baos.flush(); 
     DataHandler dh = new DataHandler(baos.toByteArray(), rtfek.getContentType()); 
     clpbrd.setContents(dh, null); 
    } 
    catch (IOException | BadLocationException e) 
    { 
     e.printStackTrace(); 
    } 

如果你想只複製文檔的小節中,我認爲要修改這一行:

rtfek.write(baos, this.doc, int startPosition, int endPosition) 

編輯:事實證明,誰創造RTFEditorKit決定,他們並不需要堅持他們的API。基本上,上面的startPosition和endPosition不起作用。

/** 
* Write content from a document to the given stream 
* in a format appropriate for this kind of content handler. 
* 
* @param out The stream to write to 
* @param doc The source for the write. 
* @param pos The location in the document to fetch the 
* content. 
* @param len The amount to write out. 
* @exception IOException on any I/O error 
* @exception BadLocationException if pos represents an invalid 
* location within the document. 
*/ 
public void write(OutputStream out, Document doc, int pos, int len) 
    throws IOException, BadLocationException { 

     // PENDING(prinz) this needs to be fixed to 
     // use the given document range. 
     RTFGenerator.writeDocument(doc, out); 
} 
0

嘗試使用系列化。 喜歡的東西

public static DefaultStyledDocument cloneStyledDoc(DefaultStyledDocument source) { 
    try { 
     DefaultStyledDocument retDoc = new DefaultStyledDocument();  

     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     ObjectOutputStream oos = new ObjectOutputStream(bos); 
     oos.writeObject(source); // write object to byte stream 

     ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());    
     ObjectInputStream ois = new ObjectInputStream(bis); 
     retDoc = (DefaultStyledDocument) ois.readObject(); //read object from stream 
     ois.close();   
     return retDoc; 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 
    return null;   
} 

窺探礁Horstmann`s書http://horstmann.com/corejava.html