Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

java - How to reach css and image files from the html page loaded by javafx.scene.web.WebEngine#loadContent?

I have a String HTML content which is loaded into webEngine by loadContent() method. I have also some css and image files used in this page. Although I put these file into the same package of java class, the loaded page cannot find them. Looked for API docs and web, but could not find any appropiate similar solutions. How I load these files?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can place your string html content in a file in the same package as the Java class and use the engine.load(String url) method instead:

engine.load(getClass().getResource("mypage.html").toExternalForm());

When you do this, all relative links in the html page will resolve to resources (e.g. css and image files) in your Java package.

Beware that if you are loading a resource that is located in a jar file, that the jar: protocol does not understand relative links with parent specifiers. E.g., <img src="../images/image.png"/> will not work, but <img src="/images/image.png"/> or <img src="images/image.png"/> will as long (as you put the image in the appropriate location in the jar file). The file: protocol does not have such restrictions and .. relative links will work fine when the resources are loaded using it.

If the html string is dynamically generated by your java code rather than static, then Sergey's solution is probably best.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...