Input Prompt Pattern in GWT
For a GWT project I'm working on, I've reached a point where I wanted to apply input prompts to a text box; this doesn't seem to be something that's built in to the basic GWT framework, or an easily-located extension. For that matter, I couldn't find anyone who'd done it and blogged about it, although it might be that they've used different terminology.
I thought it was worth a quick experiment to see how easy they would be to apply, and this is what I came up with:
package com.codiform.gwt.widget;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
public class InputPrompt implements BlurHandler, FocusHandler {
private String promptText;
public InputPrompt( String text, TextBox... inputs ) {
this.promptText = text;
for( TextBox item : inputs ) {
apply( item );
}
}
public void apply( TextBox input ) {
input.addBlurHandler( this );
input.addFocusHandler( this );
applyPrompt( input );
}
public void onBlur( BlurEvent event ) {
TextBox blurred = (TextBox) event.getSource();
applyPrompt( blurred );
}
private void applyPrompt( TextBox input ) {
if( input.getText().isEmpty() ) {
input.setText( promptText );
input.addStyleName( "inputPrompt" );
}
}
public void onFocus( FocusEvent event ) {
TextBox focused = (TextBox) event.getSource();
if( promptText.equals( focused.getText() ) ) {
focused.setText( "" );
focused.removeStyleName( "inputPrompt" );
}
}
}
The final version has some project-specific tweaks (interface for the textbox to make this code testable with mocks, a style name in the project namespace), but for the most part the above code seems to do the trick well and I'll be applying it shortly.
No comments:
Post a Comment