问题
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