How to show images in

2019-07-22 15:01发布

问题:

Is it possible to show images in <option> elements rendered by <h:selectOneMenu> tag of JSF?

I use <f:selectItems> to generate the options that I get from the database. But the content I want to show in <h:selectOneMenu> is the image associated with each item.

How can I achieve that?

回答1:

It is impossible to embed images within JSF's <h:selectOneMenu>/<f:selectItem>/<f:selectItems>, as there are no attributes designed for that purpose. Moreover, there is hardly a cross-browser compatible solution for that.

Though you could use a component library for that, like PrimeFaces. It has <p:selectOneMenu> component that basically wraps <select>/<option> with some HTML/jQuery magic, so that a 'substitute' is displayed onscreen. Example usage can be found in a showcase example. To recite it:

<p:selectOneMenu value="#{autoCompleteBean.selectedPlayer2}" converter="player" var="p">  
    <f:selectItem itemLabel="Select One" itemValue="" />  
    <f:selectItems value="#{autoCompleteBean.players}" var="player" itemLabel="#{player.name}" itemValue="#{player}"/>  

    <p:column>  
        <p:graphicImage value="/images/barca/#{p.photo}" width="40" height="50"/>  
    </p:column>  

    <p:column>  
        #{p.name} - #{p.number}  
    </p:column>  
</p:selectOneMenu>  

Of course, you can load the images in a different manner.