Saturday, May 3, 2008

GWT in-place-editor

The in place editor is one of the simplest yet powerful feature brought by Ajax.
I wrote two such editors last year, one using javascript and one leveraging Prototype as an exercise. Recently I started to study GWT more in depth and I found fun to write a GWT version of the in place editor.
I used the TextBox and Label widgets that will be used to display and edit the label.
The DeckPanel panel is used to alternate the display between the text box and the label widgets.
The interaction is performed using listeners. The ClickListener on the label copies the label value to the text box and switch the deck panel to show the text box. The KeyboadListener allows on the enter keystroke to copy the edited value to the label and switch back the deck panel to show the label.

public void onModuleLoad()
{
final DeckPanel deck = new DeckPanel();
final Label label = new Label("Initial Value");
final TextBox text = new TextBox();

// Wire the widgets
deck.add(label);
deck.add(text);
deck.showWidget(0);

//
label.addClickListener(new ClickListener()
{
public void onClick(Widget widget)
{
String value = label.getText();
text.setText(value);
deck.showWidget(1);
text.setFocus(true);
}
});

//
text.addKeyboardListener(new KeyboardListenerAdapter()
{
public void onKeyPress(Widget widget, char c, int i)
{
if (c == KEY_ENTER)
{
String value = text.getText();
label.setText(value);
deck.showWidget(0);
}
else if (c == KEY_ESCAPE)
{
deck.showWidget(0);
}
}
});

//
VerticalPanel vp = new VerticalPanel();
vp.add(deck);
RootPanel.get().add(vp);
}


The demo is available here.

2 comments:

Dion Almaer said...

Julien,

Do you have the GWT version online somewhere to check out?

Cheers,

Dion Almaer
ajaxian.com

Julien Viet said...

Dion, I do have upload a demo that is linked in the blog post.

I have added a bit of usability in the code: the focus is set on the textbox when it is shown and on a key escape the label is shown but the value remains unchanged.