Implementing alpha-numeric TextBox - gwt

I am trying to implement a alpha-numeric textbox with this code:
textBoxNewPassword.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
char keyCode = event.getCharCode();
TextBox sender = (TextBox) event.getSource();
if (!Character.isLetterOrDigit(keyCode)
|| !(keyCode == KeyCodes.KEY_TAB)
|| !(keyCode == KeyCodes.KEY_BACKSPACE)
|| !(keyCode == KeyCodes.KEY_LEFT)
|| !(keyCode == KeyCodes.KEY_RIGHT)
)
sender.cancelKey();
}
});
It works however, Backspace and Tab wont work, which is needed to erase something that user has type and to jump to another form fields.
Any ideas what's missing in this code?

tb.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
TextBox sender = (TextBox) event.getSource();
int keyCode = event.getNativeEvent().getKeyCode();
if (!(Character.isLetterOrDigit(event.getCharCode()))
&& !(keyCode == KeyCodes.KEY_TAB)
&& !(keyCode == KeyCodes.KEY_BACKSPACE)
&& !(keyCode == KeyCodes.KEY_LEFT)
&& !(keyCode == KeyCodes.KEY_RIGHT)) {
sender.cancelKey();
}
}
});
This looks like it works.

I think the problem is with your conditions. Think about it like this: if the user hits Tab, then it won't be a letter or digit, so it cancels the key. You'd like to cancel only if it isn't any of the keys you would like, not if it isn't all of the keys (at once). If you change then to && instead it should work.
if (!Character.isLetterOrDigit(keyCode)
&& !(keyCode == KeyCodes.KEY_TAB)
&& !(keyCode == KeyCodes.KEY_BACKSPACE)
&& !(keyCode == KeyCodes.KEY_LEFT)
&& !(keyCode == KeyCodes.KEY_RIGHT)
)
sender.cancelKey();
If it isn't a letter or digit, and if it isn't a tab, and if it isn't a backspace, and not a left, and not a right, then cancel.

DTing is on the right track, but you can't be sure that you get the correct keycode (browser dependent) in the KeyPressEvent, you should use it in combination with a KeyDown handler. Especially things like backspace and delete is handled differently.
Source: http://code.google.com/p/google-web-toolkit/issues/detail?id=4212 and http://www.quirksmode.org/js/keys.html

Related

GWT TextBox KeyUpHandler issue

I am trying to check if the user has not entered anything in a TextBox by using the onKeyUp method of KeyUpHandler and chacking if value.length is 0 or not.
When I test it in a browser the condition passes as true but when I test it in Android mobile it doesn't detect whether the TextBox value is 0. Please suggest. I am to new to GWT.
Code:
final E12TextBox newPasswordPwd = new E12TextBox();
newPasswordPwd.addKeyUpHandler(new KeyUpHandler()
{
#Override
public void onKeyUp(KeyUpEvent event)
{
String newPass = newPasswordPwd.getText();
if(newPass.length() != 0 && !newPass.isEmpty())
{
newPassImg.setStyleName("rightPass");
confirmPasswordPwd.setEnabled(true);
}
else
{
newPassImg.setStyleName("wrongPass");
confirmPasswordPwd.setEnabled(false);
}
}
});
You should use getValue() instead of getText(), because getText may return a null value, in which case length() will throw an exception.

Mnemonics in GWT

I would like to create as Java Swing Mnemonics with GWT . But I don't know how to figure it out. I have googled for it but I didn't fond any sample codes for it . I want to bind some keyboard shortcut keys on my buttons. How can I achieve it ? Any suggestions would be really appreciated !
In general you can handle global keyboard shortcusts using a NativePreviewHandler. An example of this can you see here:
NativePreviewHandler nativePreviewHandler = new NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (event.getTypeInt() != Event.ONKEYDOWN) {
return;
}
final NativeEvent nativeEvent = event.getNativeEvent();
final boolean altKey = nativeEvent.getAltKey();
final boolean ctrlKey = nativeEvent.getCtrlKey();
if(altKey && ctrlKey && nativeEvent.getKeyCode() == 'A') {
// Do Something
}
}
};
Event.addNativePreviewHandler(nativePreviewHandler);
But as far as I klnow, there's no generic way build into GWT to handle some kind of Action that is bound to a button/Menu as well as a keyboard shortcut. You will have to implement such an abstraction by yourselves.
I hope this code will help you. Here we are adding a key down handler on document element.
RootPanel.get().addDomHandler(new KeyDownHandler() {
#Override
public void onKeyDown(KeyDownEvent event) {
if (event.isControlKeyDown()) {
char ch = (char) event.getNativeKeyCode();
if (ch == 's' || ch == 'S') {
// do operation for Ctrl+S
} else if (ch == 'c' || ch == 'C') {
// do operation for Ctrl+C
}
// add more or use switch case
}
}
}, KeyDownEvent.getType());

Issue with Gwt-Radio Button

I am using same group name for two of my GWT-RadioButtons. When I click one of these, another one gets unchecked, which is good. But programmatically (when i do debug) the other radio button value is still remained as 'true' . As per my requirement it should be false. I am thinking that it is problem of GWT-RadioButton Group concept.
Does this problem of GWT - RadioButton?
The below is code snippet
indiaRadioBtn.setValue(true);
indiaRadioBtn.addClickHandler(new IndianRadioClickHandler());
othersRadioBtn.addClickHandler(new InternationalRadioClickHandler());
if (contactInfo != null) {
if (contactInfo.getPostalAddress().getCountry() != null) {
othersRadioBtn.setValue(true);
}
if (indiaRadioBtn.getValue()) {
index = -1;
for (StateOrProvince stateOrProvince : StateOrProvince.values()) {
index++;
if ((contactInfo.getPostalAddress().getState() != null)
&& contactInfo.getPostalAddress().getState().equals(stateOrProvince.name())) {
stateListBox.setSelectedIndex(index);
}
}
} else {
//some code }
class IndianRadioClickHandler implements ClickHandler {
#Override
public void onClick(ClickEvent event) {
//newOrUpdateContactInfoFormPanel.clear();
ContactInfo contactInfo = getSelectedContactInfo();
/**
* Used same panel and elements for both addresses, so clearing address for Indian.
*/
if (contactInfo != null) {
if (contactInfo.getPostalAddress().getCountry() != null
|| title.equals("Create New Address")) {
contactInfo = null;
}
}
newOrUpdateContactInfoFormPanel.add(getCompleteFormPanel(contactInfo));
}
}
if contactInfo != null then it is executing that loop, i am setting othersRadioBtn.setValue(true);
So my other radio button is should set to false according to group concept.. but it is not doing its job.

OpenXml - iterate through a paragraph's runs and find if a run has italic or bold text

I am trying to iterate through paragraph runs, find if a run has italized/bold text and replace that text with something else.
Which is the best method in terms of performance.
If you are interested only in inline tags, the following code can help. Just change the Convert() method to whatever you want.
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
class Program
{
static void Main(string[] args)
{
using (var doc = WordprocessingDocument.Open(#"c:\doc1.docx", true))
{
foreach (var paragraph in doc.MainDocumentPart.RootElement.Descendants<Paragraph>())
{
foreach (var run in paragraph.Elements<Run>())
{
if (run.RunProperties != null &&
(run.RunProperties.Bold != null && (run.RunProperties.Bold.Val == null || run.RunProperties.Bold.Val) ||
run.RunProperties.Italic != null && (run.RunProperties.Italic.Val == null || run.RunProperties.Italic.Val)))
Process(run);
}
}
}
}
static void Process(Run run)
{
string text = run.Elements<Text>().Aggregate("", (s, t) => s + t.Text);
run.RemoveAllChildren<Text>();
run.AppendChild(new Text(Convert(text)));
}
static string Convert(string text)
{
return text.ToUpper();
}
}
It depends on whether you want to count inherited bold/italic from styles or are just interested in inline bold/italic tags.

Allow only numbers in textbox in GWT?

I have a requirement where i need to allow only numbers in text box. if user tries to enter any other character other than numbers then we need to cancel the event. Please help me how to achieve this?
Thanks!
You just have to validate the users input on a certain event. It can be e.g. on every keystroke (KeyPressEvent), when the TextBox loses focus (ValueChangeEvent), on a button press (ClickEvent), and so on. You implement an event handler, e.g. KeyPressHandler and register your implementation with the TextBox. Then in your handler you validate the TextBox value and if it contains something else than numbers, you just return from the method, probably somehow telling the user that the value was invalid.
Something like this:
final TextBox textBox = new TextBox();
textBox.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
String input = textBox.getText();
if (!input.matches("[0-9]*")) {
// show some error
return;
}
// do your thang
}
});
If you have a lot of validation to do, you probably want to introduce some validation framework which saves you from a lot of reinventing the wheel. There may be better alternatives nowadays but personally I have been quite satisfied with the GWT-VL validation framwork.
The following is a more generic approach and allows for code reuse. You can use the NumbersOnly handler for any textbox (of the same class) you wish.
intbox1.addKeyPressHandler(new NumbersOnly());
intbox2.addFocusHandler(new OnFocus());
//inner class
class NumbersOnly implements KeyPressHandler {
#Override
public void onKeyPress(KeyPressEvent event) {
if(!Character.isDigit(event.getCharCode()))
((IntegerBox)event.getSource()).cancelKey();
}
}
class NumbersOnly implements KeyPressHandler {
#Override
public void onKeyPress(KeyPressEvent event) {
if (!Character.isDigit(event.getCharCode())
&& event.getNativeEvent().getKeyCode() != KeyCodes.KEY_TAB
&& event.getNativeEvent().getKeyCode() != KeyCodes.KEY_BACKSPACE){
((IntegerBox) event.getSource()).cancelKey();
}
}
}
I added other exceptions for example the possibility to copy the number. It still prevents the pasting of things from clipboard.
public class NumbersOnlyKeyPressHandler implements KeyPressHandler {
#Override
public void onKeyPress(KeyPressEvent event) {
switch(event.getNativeEvent().getKeyCode()) {
case KeyCodes.KEY_TAB:
case KeyCodes.KEY_BACKSPACE:
case KeyCodes.KEY_DELETE:
case KeyCodes.KEY_LEFT:
case KeyCodes.KEY_RIGHT:
case KeyCodes.KEY_UP:
case KeyCodes.KEY_DOWN:
case KeyCodes.KEY_END:
case KeyCodes.KEY_ENTER:
case KeyCodes.KEY_ESCAPE:
case KeyCodes.KEY_PAGEDOWN:
case KeyCodes.KEY_PAGEUP:
case KeyCodes.KEY_HOME:
case KeyCodes.KEY_SHIFT:
case KeyCodes.KEY_ALT:
case KeyCodes.KEY_CTRL:break;
default:
if(event.isAltKeyDown() || (event.isControlKeyDown() && (event.getCharCode() != 'v'&& event.getCharCode() != 'V')) )
break;
if(!Character.isDigit(event.getCharCode()))
if(event.getSource() instanceof IntegerBox)
((IntegerBox)event.getSource()).cancelKey();
}
}
}
Replace your TextBox with either an IntegerBox or LongBox.
This is not semantically the same as only allowing digits, but it's arguably better in most use cases.
You will also get the in and out integer parsing done for free.
Try this one:
public void onKeyPress(KeyPressEvent event) {
if(event.getNativeEvent().getKeyCode()!=KeyCodes.KEY_DELETE &&
event.getNativeEvent().getKeyCode()!=KeyCodes.KEY_BACKSPACE &&
event.getNativeEvent().getKeyCode()!=KeyCodes.KEY_LEFT &&
event.getNativeEvent().getKeyCode()!=KeyCodes.KEY_RIGHT){
String c = event.getCharCode()+"";
if(RegExp.compile("[^0-9]").test(c))
textbox.cancelKey();
}
}
you can validate it through javascript method:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
your text box will be like this
<input class="txtStyle" type="text" autocomplete="off" onkeypress ="return isNumberKey(event);" />
The ValueBox is not primary designed to filter input.
Why? Because the user will count your app enter into ANR or corrupted when he presses keys of desktop keyboard, yes?
That s not a phone with its separated types of keyset, yes?
So the only solution here is to signal people they put in wrong characters by , e.g., red coloring.
Let me submit an example code:
IntegerBox field = new IntegerBox();
field.setStyleName("number_ok");
field.addKeyUpHandler(event -> {
String string = field.getText();
char[] harfho = string.toCharArray();
for (char h : harfho) {
try {
Integer.parseInt(""+h);
} catch (NumberFormatException e) {
field.setStyleName("number_error");
return;
}
}
field.setStyleName("number_ok");
});
and in css:
.number_error{
background-color: red;
}
.number_ok{
background-color: transparent;
}
I had the same issue (using an IntegerBox which is more or less the same thing) and did it like this;
fieldName.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
// Prevent anyone entering anything other than digits here
if (!Character.isDigit(event.getCharCode())) {
((IntegerBox) event.getSource()).cancelKey();
return;
}
// Digits are allowed through
}
});