So my HTML is this.
<!DOCTYPE HTML>
<html>
<body >
<h1 style="background-color:lightblue">This is a h1</h1>
<img src="haha.jpg" alt="W3Schools.com" width="104" height="142" >
</p>
</body>
</html>
This is how I load the HTML:
JEditorPane je = new JEditorPane();
je.setEditable(false);
je.setContentType("text/html");
FileReader fr = new FileReader("testPage.html");
BufferedReader br = new BufferedReader(fr);
String text = "";
String inputLine = br.readLine();
while(inputLine!=null){
text += inputLine+"\n";
inputLine=br.readLine();
}
je.setText(text);
SwingNode sn = new SwingNode();
sn.setContent(je);
The h1 part works perfectly, but the image part does not show up, which shows up in .html file. So I want to know if there is any way to make image in HTML show up? If JEditorPane
can't do it, what other component will show the html WITH images?
Help Appreciated.
Since you're using SwingNode
, your application actually uses JavaFX.
JavaFX has a web browser component, you can read more about it here:
Overview of the JavaFX WebView
Component
Here's a short example how to use it:
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.load(url);
url
can be an address like "http://example.com"
or it can point to a file or resource like:
Paths.get("testPage.html").toURI().toURL();
If you have the HTML content as a String
, you can load it like this:
String htmlContent = "<html>....</html>";
browser.getEngine().loadContent(htmlContent);
If you want to insert images in the htmlContent
, you can do it like this:
URL url = Main.class.getResource("haha.jpg"); // haha.jpg is next to Main class
String text = "<html><img src=\"" + url + "\" width=\"104\" height=\"142\" > </html>";
Or if you want to insert an image pointing to a fixed file on your computer, create the url
like this:
URL url = new File("C:/images/haha.jpg").toURI().toURL();
Or:
URL url = Paths.get("C:/images/haha.jpg").toUri().toURL();