Hi all,
I have created a JEditorPane which I use in a chat client, with the purpose of interpreting HTML and supporting links. It's working, but I believe I havn't come up with the optimal solution for inserting new html code. I store new strings in a StringBuffer, and then after each new string is appended, I update the HTML content using setText. See my code below.
package com.olof.chat;
import java.awt.Color;
import java.awt.Font;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.JEditorPane;
import com.olof.applet.AppletActions;
public class EditorPaneHyperlinked extends JEditorPane implements HyperlinkListener
{
private AppletActions aa;
private StringBuffer sb;
public EditorPaneHyperlinked(AppletActions aa)
{
setContentType("text/html");
addHyperlinkListener(this);
setEditable(false);
setFocusable(true);
this.aa = aa;
sb = new StringBuffer();
}
public void append(String message, Font font, Color color)
{
String html = "<span style=\"color:#"
+ Integer.toHexString(color.getRGB()).substring(2)
+ "; font-family:"
+ font.getFamily()
+ "; font-size:"
+ font.getSize()
+ "pt; font-weight:"
+ (font.getStyle() == font.BOLD ? "bold" : "")
+ "\">"
+ message
+ "</span>";
append(html);
}
public void append(String message)
{
System.out.println("Appending: " + message);
sb.append(message);
setText(sb.toString());
}
public void clear()
{
sb = new StringBuffer();
setText("");
}
public void hyperlinkUpdate(HyperlinkEvent ev) {
System.out.println("hyperlink event");
System.out.println("type: "+ev.getEventType());
System.out.println("url: "+ev.getURL());
if (ev.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
{
System.out.println("goTo: "+ev.getURL());
//applet.goTo(ev.getURL(), "_blank");
aa.action();
}
}
public void newLine()
{
append("<br/>");
}
}
Optimally, I believe I would use something like
doc = getDocument;
doc.insert();
However, if I do that, it does not interpret the HTML anymore. Perhaps I need to use a HTMLDocument, but how do I achieve that?