I want to remove the first line in jtextpane and setting setContentType("text/html") at the same time.

setContentType("text/html");

Element root = getDocument().getDefaultRootElement();
Element firstLine = root.getElement(0);
getDocument().remove(firstLine.getStartOffset(), firstLine.getEndOffset());

When I use setContentType("text/html") in the code it does not remove the first line.

I don't know, but you could try printing the contents of firstLine to see what's happening. Maybe it's something that's not displayed, like "<html>" ???

  • code (skeleton, logics) is correct,
  • not reason to setContentType("text/html"); at runtime

I get an exception.

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

when using setContentType("text/html");

How many times have we said this in the Java forum...
Never NEVER NEVER do this when writing new code:

} catch (Exception e) {
}

If/when there is an error you just told Java that you didn't want to know anything about it, and please discard the detailed error message that Java just created for you.
ALWAYS put an e.printStackTrace(); in your catch blocks until/unless you have a good reason to do something else.

This did not solve the problem I am having. I just forget to write something in catch block.

Can anybody help? I would appreciated.

I would recommend if this thread is not solved, that you do not mark it as such.

It's not enough to tell us "I got an exception". You need to post the exact complete output from the printStackTrace().

This is the exception I got

javax.swing.text.BadLocationException: Invalid remove

The code works fine if I commented setContentType("text/html");

You need to post the exact complete output from the printStackTrace().

Despite your unwillingness to supply all the relevant info, I'll give you this as a present:
the remove method does NOT take two offsets as parameters. Check the api doc for the correct parameters. YOu will see that this bug is going to be able to bite you regardless of setting a doc type.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.