Thursday, 4 August 2011

SmartGwt - Make TextAreaItem readonly

The readonly attribute is not supported on TextAreaItem. Instead there are a couple of methods setDisabled(true) and setShowDisabled(false) that help disable the TextAreaItem.

But the entire TextAreaItem will be disabled and made unselectable if you set these. What if we like to retain the selectable behaviour of TextAreaItem acting truly as a readonly element and not a disabled element?

Use the following code to make TextAreaItem readonly

myTextArea.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
event.cancel();
cursorPos = myTextArea.getSelectionRange()[0];
}
});

myTextArea.addChangedHandler(new ChangedHandler() {

@Override
public void onChanged(ChangedEvent event) {
myTextArea.setSelectionRange(cursorPos, cursorPos);
}
});

The first handler makes textarea ignore any change events. But the side affect is the cursor position gets automatically changed and moves to end of text are which causes flickering and scrolling on textarea. To avoid this, attach addChangedHandler that gets called after the textarea is changed that could retain your cursor position back.

+1 if this is helpful.

1 comment:

  1. +1
    I had an issue with this "myTextArea.getSelectionRange()[0];" resulting in a null pointer under some circumstances, but with a null check this is working well.
    Thanks for quick and easy solution.

    ReplyDelete