GWT TextBox KeyUpHandler issue - gwt

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.

Related

How to disable(not remove) a column in celltable of gwt

i am new to GWT.I know tablename.removeColumn(columnname) can be used to remove the column, but instead of removing i want to disable it. Can anybody please help
thnx in advance!
There are some ways to do this, but an easy and clean way to do it is the following :
public static class CustomTextInputCell extends TextInputCell {
#Override
public void render(Context context, String value, SafeHtmlBuilder sb) {
String url = Window.Location.getHref();
boolean isEditable = url.contains("xyz");
if (isEditable) //Condition if editable or not
super.render(context, value, sb);
else if (value != null) {
sb.appendEscaped(value);
}
}
}
The render method will be called every time this cell is rendered. So every time it will check if the condition is met to be enabled or not.
This allows you to keep all the functionality of an editable cell but disable it easily when the condition is met.
You use it like this
Column<YOUR_OBJECT_HERE, String> column = new Column<YOUR_OBJECT_HERE, String>(new CustomTextInputCell());
cellTable.addColumn(column , "YOUR_HEADER_HERE");
I ended up creating a new component that has the columns that i want and called that component based on the url
String url = Window.Location.getHref();
boolean value = url.contains("xyz");
if(value)
{
component.setEnable(true);
}
else{
componentprevious.setEnable(true);
}
enter code here

Dynamically and Programatically Uncheck a CheckboxCell

I have a Datagrid with a CheckboxCell column. There will be some rows that cannot be checked, and the way I would like to implement this would be to handle the "checked" event and cancel it if some criteria is met. Here is the code I have tried:
Column<Job, Boolean> selectColumn = new Column<Job, Boolean>(new CheckboxCell()) {
#Override
public Boolean getValue(Job job) {
// do I uncheck the cell here?
return JobDataGrid.this.jobSelection.isSelected(job);
}
#Override
public void onBrowserEvent(Cell.Context context, Element elem, Job object, NativeEvent event)
{
super.onBrowserEvent(context, elem, object, event);
String eventType = event.getType();
if ("change".equals(eventType)) {
// do I uncheck the cell here?
}
}
};
How do I handle the event and set the checkbox to be unchecked?
If you want to prevent the change in a checkbox, you can simply cancel the native event inside your onBrowserEvent method:
event.preventDefault();
Note that if you don't update your object when a checkbox is clicked, you can always refresh() your DataGrid and the checkbox will be displayed in its original state.
If you want to make a check box uncheckable, from the UX perspective it is better be disabled.
You can create a custom check box cell where you can control every aspect of rendering of the element including disabled state:
public class UncheckableCheckboxCell extends CheckboxCell {
interface Template extends SafeHtmlTemplates {
#Template("<input type=\"checkbox\" tabindex=\"-1\" checked/>")
SafeHtml INPUT_CHECKED();
#Template("<input type=\"checkbox\" tabindex=\"-1\"/>")
SafeHtml INPUT_UNCHECKED();
#Template("<input type=\"checkbox\" tabindex=\"-1\" disabled=\"disabled\"/>")
SafeHtml INPUT_UNCHECKED_DISABLED();
}
private static UncheckableCheckboxCell.Template template = GWT.create(UncheckableCheckboxCell.Template.class);
public UncheckableCheckboxCell(boolean dependsOnSelection, boolean handlesSelection) {
super(dependsOnSelection, handlesSelection);
}
#Override
public void render(Context context, Boolean value, SafeHtmlBuilder sb) {
// Get the view data.
Object key = context.getKey();
Boolean viewData = getViewData(key);
if (viewData != null && viewData.equals(value)) {
clearViewData(key);
viewData = null;
}
if (value != null && ((viewData != null) ? viewData : value)) {
sb.append(template.INPUT_CHECKED());
} else if (value == null) {
//use null value as an indicator of unchecked and disable state
sb.append(template.INPUT_UNCHECKED_DISABLED());
} else {
sb.append(template.INPUT_UNCHECKED());
}
}
}
Then inside your getValue() method you can return null when you want the check box to be unchecked/disabled:
#Override
public Boolean getValue(Job job) {
// is my job checkable?
if (job.checkable()) {
//return null explicitly so my custom cell knows it should be rendered as disabled
return null;
} else {
return JobDataGrid.this.jobSelection.isSelected(job);
}
}

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
}
});

GWT checking if textbox is empty

Im working on a school project and i'm trying to check in GWT if a textbox i create is empty or not. I have done the exact same thing on another project and there it worked fine. i have searched for the answer here and on google but couldn't find any answer.
voornaamTB = new TextBox();
voornaamTB.setText(null);
ok.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (voornaamTB != null) {
System.out.println("not empty");
} else {
System.out.println("empty");
}
}
});
Something like:
if(!voornaamTB.getText().isEmpty()) { ...
will work. You're currently testing to see whether the TextBox itself is null, which it isn't as you initialized it on the first line.
You probably don't need the setText(null) after immediately creating it.
Your object is not empty, so you can get only not empty. try this
voornaamTB = new TextBox();
voornaamTB.setText(null);
ok.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (voornaamTB.getText() != null) {
System.out.println("not empty");
} else {
System.out.println("empty");
}
}
});

Hitting enter in TextBox in google web toolkit in firefox causes form submit, but not IE

gwt 1.6.4 ie 8 ff 3.6.13
My users want to be able to hit enter to submit a form in a gwt TextBox. So I wrote the code, got it working then found that it double submitted (in firefox)
So I took it out and noticed that hitting enter in firefox causes a page submit, but in IE it doesn't.
So either I have it half working (one of two popular browsers) or it works in ie and double submits in firefox.
Suggestions?
I've seen lots of comments about this but nothing specific to gwt.
input.addKeyPressHandler(new KeyPressHandler()
{
#Override
public void onKeyPress(KeyPressEvent event_)
{
boolean enterPressed = KeyCodes.KEY_ENTER == event_
.getNativeEvent().getKeyCode();
if (enterPressed)
{
//submit logic here
}
}
});
Here is a handler that I developed to do a submit on enter that also tries to eliminate submission when the user uses enter to select an option in a field such as auto complete. It's not perfect, but it works. If the item I add to a form is an instance of FocusWidget I add the following handler.
protected final KeyPressHandler submitOnEnterHandler = new KeyPressHandler()
{
#Override
public void onKeyPress(KeyPressEvent event)
{
char charCode = event.getCharCode();
if (submitOnEnter && (charCode == '\n' || charCode == '\r'))
{
final Object source = event.getSource();
final String beforeText;
if (source instanceof TextBoxBase)
beforeText = ((TextBoxBase) source).getText();
else
beforeText = null;
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
#Override
public void execute()
{
String afterText;
if (source instanceof TextBoxBase)
afterText = ((TextBoxBase) source).getText();
else
afterText = null;
if (beforeText.equals(afterText))
submit();
}
});
}
}
};