TurboManage

David Chandler's Journal of Java Web and Mobile Development

  • David M. Chandler


    Web app developer since 1994 and Google Cloud Platform Instructor now residing in Colorado. Besides tech, I enjoy landscape photography and share my work at ColoradoPhoto.gallery.

  • Subscribe

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 223 other followers

  • Sleepless Nights…

    February 2010
    S M T W T F S
     123456
    78910111213
    14151617181920
    21222324252627
    28  
  • Blog Stats

    • 1,029,259 hits

Archive for February 16th, 2010

A TextBox with input prompt for GWT

Posted by David Chandler on February 16, 2010

Here’s a nifty GWT widget that displays a prompt in a text box and erases it when you click or type in the text box. It looks simple, but is actually quite clever in design as it is entirely self-contained. Thanks to Geoffrey Wiseman for the inspiration for this.

package com.turbomanage.gwt.client.ui.widget;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.TextBox;

public class PromptedTextBox extends TextBox implements KeyPressHandler, FocusHandler, ClickHandler
{
	private String promptText;
	private String promptStyle;

	public PromptedTextBox(String promptText, String promptStyleName)
	{
		this.promptText = promptText;
		this.promptStyle = promptStyleName;
		this.addKeyPressHandler(this);
		this.addFocusHandler(this);
		this.addClickHandler(this);
		showPrompt();
	}

	public void showPrompt()
	{
		this.addStyleName(promptStyle);
		this.setText(this.promptText);
	}

	public void hidePrompt()
	{
		this.setText(null);
		this.removeStyleName(promptStyle);
	}

	@Override
	public void onKeyPress(KeyPressEvent event)
	{
		if (promptText.equals(this.getText())
			&& !(event.getNativeEvent().getKeyCode() == KeyCodes.KEY_TAB))
		{
			hidePrompt();
		}
	}

	@Override
	public void onFocus(FocusEvent event)
	{
		this.setCursorPos(0);
	}

	@Override
	public void onClick(ClickEvent event)
	{
		if (promptText.equals(this.getText()))
			hidePrompt();
	}
}

All that’s needed to round it out is a little CSS to lighten up the prompt text:

.prompt {
	color: #999;
}

Enjoy!

Posted in Google Web Toolkit | 7 Comments »

 
%d bloggers like this: