问题
I'm studying JSF 2.0 and I have an ImageIcon
in a class. Can I show this ImageIcon
to JSF page?
回答1:
There's some major conceptual misunderstanding going on.
Java/JSF runs on webserver and produces HTML. HTML runs on webbrowser and can reference CSS/JS/image files by (relative) URLs in <link>
, <script>
and <img>
elements. ImageIcon
is part of Swing and has nothing to do with this all.
Swing does not produce any HTML at all. When you still attempt to run it "the Swing way" in a Java class which is invoked by a HTTP request, such as a JSF backing bean class or even a "plain vanilla" servlet class, then it would only be shown to the screen which is attached to the physical machine where the webserver runs, not the one where the webbrowser runs (which is exactly where HTML runs).
Ultimately, you need to show the icon by normal HTML means. That is, using the <img>
element, or perhaps on a block element with a CSS background-image
property. Either way, they have to point a valid URL which returns an image (that is, when the enduser enters exaclty that URL in the browser's addressbar, it should see the image in its entirety). Normally, this is to be achieved by placing the image file in the public webcontent (there where you also store your JSF (XHTML/JSP) pages.
In JSF means, you can procude a HTML <img>
element using <h:graphicImage>
component. Provided the following webcontent folder structure
WebContent
|-- META-INF
|-- WEB-INF
|-- resources
| `-- images
| `-- icon.png
`-- index.xhtml
and the following component in index.xhtml
<h:graphicImage name="images/icon.png" />
then the enduser should be able to see the desired image by just opening index.xhtml
.
An alternative is to create a Swing based applet or webstart (JNLP) application which displays the image as an ImageIcon
and finally embed it via HTML <applet>
or <object>
element in the webpage. But that's plain clumsy.
回答2:
Short of rendering it to an image on the server side, I'd say an applet would be the only other way to get an ImageIcon
into a web page.
来源:https://stackoverflow.com/questions/14249383/show-imageicon-from-class-to-jsf-page