How do I style HTML correctly using an external CSS file? [closed]

爱⌒轻易说出口 提交于 2019-12-13 10:14:49

问题


I want to be able to load an HTML document from the Internet, display it in a JEditorPane and have it styled in Java using both an external CSS file and/or from any <style>...</style> tags. What I'm doing right now is using jEditorPane.setPage(URL); and it's not correctly styled.


回答1:


Based on the JavaDoc - jEditorPane supports the bleeding edge HTML 3.2 and CSS1 so the short answer is, you really don't want to try rendering modern web pages with it.

However, you may be able to do this:

import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

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

URL url = new URL(location of your stylesheet);
StyleSheet styleSheet = new StyleSheet();
styleSheet.importStyleSheet(url)
kit.setStyleSheet(styleSheet);



回答2:


I don't think you can render modern HTML with a JEditorPane. From the docs:

By default, the following types of content are known:

...

text/html

HTML text. The kit used in this case is the class javax.swing.text.html.HTMLEditorKit which provides HTML 3.2 support.

HTML 3.2, as defined last century, ie no CSS/CSS2.

You could use an external library to render HTML as we know it now. A little bit of google work will turn up a couple of options, or you can look here.



来源:https://stackoverflow.com/questions/14063715/how-do-i-style-html-correctly-using-an-external-css-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!