2011-05-06 78 views
2

正確的我已經計算出JTextArea或JTextField不支持HTML。在JEditorPane,JTextPane的JTextArea中的HTML

我想將文本添加到像JTextArea一樣的「屏幕」,稍後繼續向其添加文本。

我試着用的JTextArea其表現的很出色,但它不支持的格式似乎...

所以我嘗試使用的JEditorPane的子類JTextPane的,但是這一次沒有它的附加功能......

有人可以在正確的方向引導我如何輕鬆地將文本附加到JTextPane或格式化JTextArea。

或者,如果有任何其他成分更好地爲這個請告訴我:)

的更新方法是由做這行的多個對象的對象調用。這只是給了一些字符串格式化,然後放在一個很好的框架來顯示用戶。

@Override 
public void update(String channel, String sender, String message) { 

    if(channel.equals(this.subject) || sender.equals(subject)){ 
     StringBuffer b = new StringBuffer(); 
     b.append("<html>"); 
     b.append("<b>"); 
     b.append("</b>"); 
     b.append("["); 
     b.append(sender); 
     b.append("] : "); 
     b.append("</b>"); 
     b.append(message); 
     b.append("</html>"); 
     b.append("\n"); 

     chatArea.append(b.toString()); 
    } 

回答

4

可有人的GUID我在正確的方向如何我可以輕鬆地添加文本到的JTextPane

Document doc = textPane.getDocument(); 
doc.insertString(doc.getLength(), "some text", green); 

而且使用屬性,而不是HTML,它容易得多。例如,你可以定義「綠色」屬性是:

SimpleAttributeSet green = new SimpleAttributeSet(); 
StyleConstants.setForeground(green, Color.GREEN); 
0

對於格式化輸出JEditorPAne可能是最好的選擇。

您可以使用JEditorPane的getText()方法獲取當前位於窗格中的文本,然後附加新文本並調用setText()將所有內容都放回。

例如

b.append(chatArea.getText()); 
    b.append("All the other text") 
    chatArea.setTExt(b.toString()); 
1

您可以使用JEditorPane中。但是當你想附加一些包含HTML標籤的字符串時,你應該執行一些方法,而不僅僅是一個insertString()方法。

例如,你有

//setup EditorPane 
JEditorPane yourEditorPane = new JEditorPane(); 
yourEditorPane.setContentType("text/html"); 

//setup HTMLEditorKit 
HTMLEditorKit htmlEditorKit = new HTMLEditorKit(); 
yourEditorPane.setEditorKit(htmlEditorKit); 

如果只使用insertString()

String htmlText = "<div class='test'><b>Testing</b></div>"; 
Document doc = yourEditorPane.getDocument(); 
doc.insertString(doc.getLength(), htmlText, null); 

的輸出將是

< DIV類= '測試'> < B>測試</b> </div>

你應該這樣做方法

htmlEditorKit.insertHTML((HTMLDocument) doc, doc.getLength(), htmlText, 0, 0, null); 

所以您editorpane輸出將

測試


最後,如果你想風格你editorpane您可以使用此方法

StyleSheet css = htmlEditorKit.getStyleSheet(); 
css.addRule(".test {color: green;}");