5

I'm trying to display HTML in my java application that has a linked stylesheet include in my HTML.

I am transforming my XML to HTML using XSLT from Java. I want to include a stylesheet so I can easily style the html output. However the stylesheet is being ignored and the html is being output normally.

To do this I am using a JEditorPane and HTMLEditorKit. I found some sample code on Dev Daily to do this.

My stylesheet is sitting on my local hard drive and I wondered if anyone knew how I could use it?

I have the following code:

JEditorPane jEditorPane = new JEditorPane();
jEditorPane.setEditable( false );

HTMLEditorKit kit = new HTMLEditorKit();
jEditorPane.setEditorKit(kit);

try {    
    kit.getStyleSheet().importStyleSheet( new URL( "file://D:\\mycssfile.css" ) );
} catch( MalformedURLException ex ) {
}

Document doc = kit.createDefaultDocument();
jEditorPane.setDocument(doc);
jEditorPane.setText(html);

In my html output from xsl the css is linked using the following - I get the same result with it included or excluded:

<link rel="stylesheet" type="text/css" href="mycss.css" />

Any ideas?

Cheers,

Andez

1
  • I think HTMLEditorKit has fairly poor support for CSS, that could be the problem Commented Oct 14, 2010 at 15:06

1 Answer 1

5

Your URL isn't valid, so it can't find your CSS file. Change it to:

kit.getStyleSheet().importStyleSheet(new URL("file:///D:/mycssfile.css"));

Or better still, instead of using a URL, add the css file to your classpath and then load it as a resource, like this:

kit.getStyleSheet().importStyleSheet(MyClassName.class.getResource("mycssfile.css"));
Sign up to request clarification or add additional context in comments.

1 Comment

I went for the kit.getStyleSheet().importStyleSheet(new URL("file:///D:/mycssfile.css")); option. Our configuration is stored relatively under the java application path so just need to figure that part out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.