2

I am currently working with a JTextPane with html in it. I set its content type to html and everything worked just fine... or so I thought.

The function of the JTextPane is to output paragraphs(with

tags), each in a different color. Each set of

tags comes equipped with an inline style attribute.

Now I am printing the

tags like this:

String myLine = "<P style=\"color:blue;" +
        "padding-left:25px;" +
        "text-indent:-25px;" +
        "font-family:Courier New;" +
        "font-size:11;"  +
        "\">" ;
doc.insertBeforeEnd(body, myLine);

Where doc is the JTextPane HTMLDocument of the JTextPane, body is the body element in my HTMLDocument.

It outputs everything just fine in the JTextPane, the text is blue, courier, 11 size with a hanging indent. PERFECT!

You would think that if you recovered the text once more you would see that P tag just the way you built it. So I recover the html inside it using getText() method: Reality

<p style="text-indent: -25px; padding-left: 25px">

when I was actually expecting to see this: Expectation

<p style="color:blue; text-indent: -25px; padding-left: 25px; font-family:Courier New; font-size:11;">

Why does it do this? Is there a way to avoid this? If I had to guess, it seems that Java extracts the text attributes so that it can more efficiently process those attributes by its own means.

However, the reason I am asking this is because once I began customizing my JTextPane more in depth, the coloring started becoming unreliable. I would rather just have the attributes directly on the inline style.

Thanks in advance, I greatly appreciate your help.


EDIT: Someone asked to see full html output before and after

tags were added.

Before:

<html>
  <head>

  </head>
  <body>

  </body>
</html>

Now I execute this code in java:

String htmlLine = "<p style=\"color:blue; " +
                             "text-indent: -25px; " +
                             "padding-left: 25px; " +
                             "font-family:Courier New; " +
                             "font-size:11;\" >" ;
try {
    doc.insertBeforeEnd(body, htmlLine);
} catch (Exception e) {
    System.err.println(e);
}

After:

<html>
  <head>

  </head>
  <body>
    <p style="text-indent: -23px; padding-left: 25px">
      First Text
    </p>
  </body>
</html>
4

1 に答える 1

1

のJavadocによるとinsertBeforeEnd()

insertAfterEndメソッドとは異なり、新しい要素は、兄弟ではなく、指定された要素の子になります。

これは、挿入された要素が子になり、親のスタイルを継承していることを意味します。内部的に挿入中に、HTMLDocumentは、親にすでに存在する子から重複するスタイル情報を削除します。だからこれがあなたが得ている理由です

<p style="text-indent: -25px; padding-left: 25px">

それ以外の

<p style="color:blue;
          text-indent: -25px;
          padding-left: 25px;
          font-family: Courier New;
          font-size:11;" >

最後にあなたの場合の原因は

  • 親に同じスタイルを設定しました。
于 2013-01-27T11:10:27.563 に答える