Mapping between selected text and HTML JEditorPane

[nobr]Hi everybody,

I use a JEditorPane to display some HTML in which my users can make selection. If a selection is made I have to retrieve the HTML which is selected in order to perform some processing.

For example:

I display the following HTML:

<html>

<head></head>

<body>

<h1>This is a page</h1>

This is text.<br />It includes a break!

</body>

</html>

Now imagine my user makes a selection in the JEditorPane, for example: "text.

It includes". I get "text. It includes" back from pane.getSelectedText(), so I miss the underlying HTML. I am looking for a way to retrieve the underlying HTML of a selection. Perhaps there is a mapping or another way to retrieve this?

Best regards,

Jethro Borsje[/nobr]

[822 byte] By [Jethroa] at [2007-11-27 10:14:31]
# 1

You can get slection start and selection end offsets and use kit's write() method passing proper document and offsets.

The writer will contains html text.

Regards,

Stas

StanislavLa at 2007-7-28 15:33:49 > top of Java-index,Desktop,Core GUI APIs...
# 2

Thank you very much for your reply, this did the trick:

EditorKit editorKit = m_pane.getEditorKit();

StringWriter sw = new StringWriter();

try

{

editorKit.write(sw, m_pane.getDocument(), m_pane.getSelectionStart(), m_pane.getSelectionEnd() - m_pane.getSelectionStart());

}

catch (IOException ex)

{

logger.error("Error writing selection", ex);

}

catch (BadLocationException ex)

{

logger.error("Error writing selection", ex);

}

sw.flush();

logger.info("String writer tostring: " + sw.toString());

Jethroa at 2007-7-28 15:33:49 > top of Java-index,Desktop,Core GUI APIs...