2009-10-06 40 views
2

我正在使用JTextPane編輯HTML。當我在GUI組件中輸入換行符並在JTextPane上調用getText()時,我得到一個帶有換行符的字符串。如果我然後創建一個新的JTextPane並傳入相同的文本,則換行符將被忽略。HTML JTextPane新行支持

爲什麼JTextPane在輸入換行符時插入了<br>標籤?有沒有一個很好的解決方法?

JTextPane test = new JTextPane(); 
    test.setPreferredSize(new Dimension(300, 300)); 
    test.setContentType("text/html"); 
    test.setText("Try entering some newline characters."); 
    JOptionPane.showMessageDialog(null, test); 
    String testText = test.getText(); 
    System.out.println("Got text: " + testText); 
    // try again 
    test.setText(testText); 
    JOptionPane.showMessageDialog(null, test); 
    testText = test.getText(); 
    System.out.println("Got text: " + testText);   

輸出示例:

<html> 
    <head> 

    </head> 
    <body> 
    Try entering some newline characters. 
What gives? 
    </body> 
</html> 

我知道我可以調用的setText之前將換行符轉換爲HTML換行,但會在HTML和BODY標籤後的換行轉換爲好,而且似乎愚蠢。

回答

8

我解決了這個問題,是我在setText中傳入的純文本。如果我撥打電話setText,則JTextPane.getText()的結果是格式良好的HTML,並且換行符正確編碼。

我相信當我打電話給JTextPane.setText("Try entering some newline characters")時,它會將HTMLDocument.documentProperties.__EndOfLine__設置爲「\ n」。此文檔屬性常量定義爲here

的解決方案是,以確保它傳遞給JTextPane.setText()方法時,你包在<p>標記文本(注意,樣式屬性用於任何後續段落):

textPane1.setText("<p style=\"margin-top: 0\">Try entering some newline characters</p>"); 

或者,你以純文本傳遞後,更換EndOfLineStringProperty(這更是一個黑客,我不會推薦它):

textPane1.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "<br/>\n") 
0

它看起來像HTMLWriter類吃了新的一行,並沒有讀取它或將其翻譯爲HTML(請參閱HTMLWriter中的第483行)。我看不出一個簡單的方法,因爲它似乎被硬編碼爲檢查'\ n'。您可能能夠將JTextPane文檔的DefaultEditorKit.EndOfLineStringProperty屬性(通過getDocument()。putProperty)設置爲<br>,然後覆蓋setText以用<替換「\ n」。儘管這樣做會按照你的建議進行,並在html,head和body標籤之間添加中斷,所以你可能只想在body標籤中進行替換。它似乎沒有一個非常簡單的方法來做到這一點。

0

我這一個半天掙扎。這在Java 7中仍然存在問題。問題是將用戶輸入的新行保存到JEditorPane中(對於HTML內容類型)。當我在用戶輸入的「\ n」處添加了一個標記鍵「\ r」(仍然需要「\ n」在編輯器中顯示新行),我才能保留HTML中的新行,然後用一個「\ n < br/>」,當我將整個內容拉出並放置在不同的JEditorPane或任何需要的HTML中時。我只在Windows上測試過。

((AbstractDocument) jEditorPane.getDocument()).setDocumentFilter(new HtmlLineBreakDocumentFilter()); 

// appears to only affect user keystrokes - not getText() and setText() as claimed 
public class HtmlLineBreakDocumentFilter extends DocumentFilter 
{ 
    public void insertString(DocumentFilter.FilterBypass fb, int offs, String str, AttributeSet a) 
         throws BadLocationException 
    { 
     super.insertString(fb, offs, str.replaceAll("\n", "\n\r"), a); // works 
    } 

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) 
     throws BadLocationException 
    { 
     super.replace(fb, offs, length, str.replaceAll("\n", "\n\r"), a); // works 
    } 
} 


String str = jEditorPane.getText().replaceAll("\r", "<br/>"); // works 
jEditorPane2.setText(str); 
+0

getText()的輸出是什麼?你有什麼? – 2012-03-04 18:40:37