Life @ NCP

not everyone needs to go outside to have fun

self-labeled buttons

Been playing with GWT ((was very shiny in May 2006)) lately – procrastinating from having to read journal papers. GWT seemed to be pretty good, I am mostly satisfied with the code I produced in terms of design. Much more satisfied than writing (and DEBUGGING) Java Script eeek. But I found the tutorial on GWT is very limited, especially around the actual widgets to create good UI. Maybe GWT users are assumed to be familiar with html/css/java script in general and therefore are proficient in creating UI.

GWT to me, brings a new level of creating UI. UI now can be created with OO concept, no more slabs of long and drowning html/javascript. A self-labeled button is a good example to showcase GWT ability.

What I usually see in the ‘Web 2.0’ app UI, is a radio button where the name of the button can be changed on the fly. See what I meant below, the state goes in order of (1) -> click ‘Unlabeled’ -> (2) -> type ‘Self-labeled’ -> (3)

self-labeledbuttons.png

When I click on the button label ‘Unlabeled’, a textarea will appear and allow me to change the label. Once I click outside the textarea, it will change back to the previous state, but with the new label.

Each of these self-labeled radio button can be created as a widget. The widget is a horizontal panel which consist of a nameless radio button, a label, and a text area. On (1), the radio button and the label are added to the panel. Clicking the label brings the state to (2) – the label is removed from the panel, and the textarea is added. When an onLostFocus event is triggered, the textarea is removed and the label is added back. Of course after the texts are matched between the two elements.

Here is some of the snippet of the code:

[cc lang=”java”]
public class SelfLabeledButton extends Composite {

public SelfLabeledButton(String label) {
button = new RadioButton(“group”,””); // nameless radio button
panel.add(button);
buttonLabel = new Label(label);
buttonLabel.addClickListener(listener);
panel.add(buttonLabel);
buttonTextArea = new TextBox();
buttonTextArea.addFocusListener(listener);

initWidget(panel);
}

private HorizontalPanel panel = new HorizontalPanel();
private RadioButton button;
private Label buttonLabel;
private TextBox buttonTextArea;
private MCListener listener = new MCListener();

private class MCListener implements ClickListener, FocusListener {

// when (1) -> (2)
public void onClick(Widget sender) {
if (sender instanceof Label) {
panel.remove(buttonLabel);
buttonTextArea.setText(buttonLabel.getText());

panel.add(buttonTextArea);
buttonTextArea.selectAll();
}
}

public void onFocus(Widget sender) {
// do nothing
}

// when (2) -> (3)
public void onLostFocus(Widget sender) {
panel.remove(buttonTextArea);
buttonLabel.setText(buttonTextArea.getText());
panel.add(buttonLabel);
}
}

}
[/cc]