Important Notice - Forums is archived
To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
Textfield change key typed to uppercase
As the title said, I'm trying to convert every key typed in textfield to upper case using keypress handler.
I used extension to achieve this. See example code below:
import com.google.gwt.event.dom.client.*;
import com.vaadin.client.*;
import com.vaadin.client.ui.*;
import com.vaadin.client.extensions.*;
import com.vaadin.shared.ui.*;
@SuppressWarnings("serial")
@Connect(TextFieldUpCase.class)
public class TextFieldUpCaseConnector extends AbstractExtensionConnector {
@Override
protected void extend(ServerConnector target) {
final VTextField tf = (VTextField) ((ComponentConnector) target).getWidget();
tf.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
char c = event.getCharCode();
if (Character.isLowerCase(c)) {
//I wish there is a method like below,
//or other ways to achieve the same result
//
//event.setCharCode(Character.toUpperCase(c));
}
}
});
}
}
There is no mechanism to intercept and altering the event like awt/swing do. So what the best solution for this problem? What can I use to achieve this?
Thanks.
Hi,
Maybe you could just convert the whole text in the input uppercase after typing?
Yes, sure... I already have that idea before.. like below snippet
@Override
public void onKeyPress(KeyPressEvent event) {
char c = event.getCharCode();
if (Character.isLowerCase(c)) {
event.preventDefault();
c = Character.toUpperCase(c);
String oldv = tf.getValue();
int cursorPos = tf.getCursorPos();
String newv = oldv.substring(0,cursorPos) + c + oldv.substring(cursorPos);
tf.setValue(newv);
tf.setCursorPos(cursorPos+1);
}
}
but are you sure this is the correct solution? IMHO this is cheated solution and it might buggy.
It is always cheating when you are working at browser level :-) If it works, don't fix it!
Could somebody take a look at the code, I have a question...
When the string we typed is longer than textfield length, why the textfield didn't scroll to cursor position just like usual.
Thanks