How to make an image button in JSF

bspoel picture bspoel · May 6, 2011 · Viewed 63k times · Source

I want to have a component that looks like a button, but instead of text it should contain an image. Because the standard button does not offer this functionality, I tried to use a <h:commandLink>:

<h:commandLink action="#{some_action}">
    <p:panel styleClass="some_style">
        <h:graphicImage value="#{some_image}">
    </p:panel>
</h:commandLink>

This doesn't work. The <h:commandLink> is translated into an <a> tag, and the <p:panel> into a <div>. <a>-tags may not contain <div>-tags, so the <div>-tag is automatically placed outside the <a>-tag. The result is that only the image is clickable, not the surrounding panel which is styled to look like a button. Is there a way to make the surrounding panel part of the link, or to put an image inside a button?

My project uses JSF and the Primefaces library:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui">

Answer

Mark picture Mark · May 6, 2011

There are a couple ways you can add an image to a commandButton:

Using the image attribute

<h:commandButton action="#{some_action}" image="button.gif" />

Absolute or relative URL of the image to be displayed for this button. If specified, this "input" element will be of type "image". Otherwise, it will be of the type specified by the "type" property with a label specified by the "value" property.

Use CSS

<h:commandButton action="#{some_action}" styleClass="button" />

.button {
    background: white url('button.gif') no-repeat top;
}