Sami
Sami

Reputation: 19

How to remove first line in JTextPane and setting setContentType("text/html")

I want to remove the first line in JTextPane and setting setContentType("text/html"); to be able to use html tags in JTextPane.

When I use this code

setContentType("text/html");

try {
  Element root = getDocument().getDefaultRootElement();
  Element firstLine = root.getElement(0);
  getDocument().remove(firstLine.getStartOffset(), firstLine.getEndOffset());
   }
catch (Exception e) {e.toString();}

I get an exception

javax.swing.text.BadLocationException: Invalid remove

if I commented setContentType("text/html"); I can be able to remove the first line from JTextPane.

Upvotes: 0

Views: 183

Answers (1)

StanislavL
StanislavL

Reputation: 57421

For the HTMLEditorKit the Element firstLine = root.getElement(0); normally returns <HEAD> but you need <BODY>. Go through the Element Tree, find the BODY and remove the first child of BODY.

UPDATE: The link shows a tool you can use to understand your Document structure. http://java-sl.com/JEditorPaneStructureTool.html

You can check which elements you have and figure out which exactly element should be removed.

Upvotes: 1

Related Questions