IgorShare Weblog

Practical Engineering

Adding Watermark to GWT Textbox widget

Posted by igormoochnick on 06/30/2009

Let’s see how we can improve our UI by adding some watermarked “spice”:

clip_image001

Let’s define the primary style for the text box (textInput) and the dependent style for the watermark (textInput-watermark):

.textInput {
	border: 1px solid #C9C7BA;
	font-family:Tahoma, Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
	padding-left: 2px;
	padding-top: 2px;
}

.textInput-watermark {
   /* background-image: url('images/overlay.gif');
   background-repeat: no-repeat;
   padding-left: 20px;
   vertical-align: middle; */
   font-style: italic;
   color: DarkGray;
}

Note that the watermark style can contain images as well (see the commented out piece).

After the styles were defined we need to add some code that will apply it to the text box. To do this I’m going to extend the default GWT TextBox. The trick is to hijack the OnBlur and OnFocus events. When the OnBlur is occurring, we’re going to show the watermark and OnFocus – hide it:

public class WatermarkedTextBox extends TextBox implements BlurHandler, FocusHandler
{
	String watermark;
	HandlerRegistration blurHandler;
	HandlerRegistration focusHandler;

	public WatermarkedTextBox( )
	{
		super();
		this.setStylePrimaryName("textInput");
	}

	public WatermarkedTextBox(String defaultValue)
	{
		this();
		setText(defaultValue);
	}

	public WatermarkedTextBox(String defaultValue, String watermark)
	{
		this(defaultValue);
		setWatermark(watermark);
	}

	/**
	 * Adds a watermark if the parameter is not NULL or EMPTY
	 *
	 * @param watermark
	 */
	public void setWatermark(final String watermark)
	{
		this.watermark = watermark;

		if ((watermark != null) && (watermark != ""))
		{
			blurHandler = addBlurHandler(this);
			focusHandler = addFocusHandler(this);
			EnableWatermark();
		}
		else
		{
			// Remove handlers
			blurHandler.removeHandler();
			focusHandler.removeHandler();
		}
	}

	@Override
	public void onBlur(BlurEvent event)
	{
		EnableWatermark();
	}

	void EnableWatermark()
	{
		String text = getText();
		if ((text.length() == 0) || (text.equalsIgnoreCase(watermark)))
		{
			// Show watermark
			setText(watermark);
			addStyleDependentName("watermark");
		}
	}

	@Override
	public void onFocus(FocusEvent event)
	{
		removeStyleDependentName("watermark");

		if (getText().equalsIgnoreCase(watermark))
		{
			// Hide watermark
			setText("");
		}
	}
}

One Response to “Adding Watermark to GWT Textbox widget”

  1. [...] Adding Watermark to GWT Textbox widget « IgorShare Weblog [...]

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>