Mnemonics in GWT - 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());

Related

Prevent <ENTER> from bubbling up from SuggestBox

I want to prevent that when the user hits ENTER to select a Suggestion in the SuggestBox, that this Key event is bubbling up.
I have this code in the wrapping Composite :
Event.addNativePreviewHandler(new Event.NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (event.getTypeInt() == Event.KEYEVENTS) {
int key = event.getNativeEvent().getKeyCode();
if (key == KeyCodes.KEY_ENTER) {
event.cancel();
}
}
}
});
But this handler is never called.
I can't tell why your method is not working. But I have an alternative approach. Add a key event listener for suggest box. If the enter key is pressed, cancel the propagation of the event.
suggestBox.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
int key = event.getNativeEvent().getKeyCode();
if (key == KeyCodes.KEY_ENTER) {
event.stopPropagation();
}
}
});
This worked better for me:
suggestBox.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
int key = event.getNativeEvent().getKeyCode();
if (key == KeyCodes.KEY_ENTER) {
event.getNativeEvent().preventDefault();
}
}
});
#Jen,
This code restricts the action of the 'enter' key-press in the textarea (if suggestBox associates with the text area), even when suggestion list is not shown.
While my suggestion list is showing, pressing the 'ENTER' key triggered the event-handler addSelectionHandler() where I want to stop the propagation (addKeyPressHandler event-handler should not be triggered)

Implementing alpha-numeric TextBox

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

GWT - Firing native KeyPressEvent doesn't work?

I want to replace a special entered character (e.g. 'A') with another one (e.g. 'B') when a user entering data in a TextBox or TextArea. My code is like below:
public void onKeyPress(KeyPressEvent event) {
if (event.getNativeEvent().getCharCode() == 65 /*for 'A'*/){
event.preventDefault();
NativeEvent event1 =
Document.get().createKeyPressEvent(false, false, false, false, 66 /* for 'B'*/);
DomEvent.fireNativeEvent(event1, theTextBox);
}
I think it should be OK (according to GWT docs), but in fact it just work until event.preventDefault(); and the rest seems ignored. I mean it just removes 'A' but doesn't fire for 'B'. Can anyone tell me the reason? or any other solution? Thanks.
try to switch from KeyPressHandler to KeyDownHandler.
public void onKeyDown(KeyDownEvent event) {
if( event.getNativeKeyCode() == 65 ) {
//do the character replacement here
}
}
Hope it will help you.

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

eclipse rcp :how to select a single cell in tableviewer?

hwo can I change the default selection behaviour of tables, I want to make a cell selected when user click it and make it editable when user double click it.
with #nonty 's help, I get what I want.
here is my cell highlighter implemention:
package com.amarsoft.rcputil;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.FocusCellOwnerDrawHighlighter;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
public class DefaultCellFocusHighlighter extends FocusCellOwnerDrawHighlighter {
public DefaultCellFocusHighlighter(ColumnViewer viewer) {
super(viewer);
}
protected boolean onlyTextHighlighting(ViewerCell cell) {
return false;
}
protected Color getSelectedCellBackgroundColor(ViewerCell cell) {
return cell.getControl().getDisplay().getSystemColor(SWT.COLOR_DARK_BLUE);
}
protected Color getSelectedCellForegroundColor(ViewerCell cell) {
return cell.getControl().getDisplay().getSystemColor(SWT.COLOR_WHITE);
}
protected Color getSelectedCellForegroundColorNoFocus(ViewerCell cell) {
return cell.getControl().getDisplay().getSystemColor(SWT.COLOR_WHITE);
}
protected Color getSelectedCellBackgroundColorNoFocus(ViewerCell cell) {
return cell.getControl().getDisplay().getSystemColor(SWT.COLOR_DARK_BLUE);
}
protected void focusCellChanged(ViewerCell newCell, ViewerCell oldCell) {
super.focusCellChanged(newCell, oldCell);
}
}
the code to use it :
TableViewerFocusCellManager focusCellManager = new TableViewerFocusCellManager(tv,new DefaultCellFocusHighlighter(tv));
ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(tv) {
protected boolean isEditorActivationEvent(ColumnViewerEditorActivationEvent event) {
return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
}
};
TableViewerEditor.create(tv, focusCellManager, actSupport, ColumnViewerEditor.TABBING_HORIZONTAL
| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
| ColumnViewerEditor.TABBING_VERTICAL | ColumnViewerEditor.KEYBOARD_ACTIVATION);
but I got new problem :
when I double click on cell to edit it's value, there is a little area at the left side of the cell is still highlighted with dark blue color
I know why :
When a text control is created with a border, the operating system includes a platform specific inset around the contents of the control.
still seeking for fixing...
Have a look at these two JFace Snippets:
Snippet036FocusBorderCellHighlighter - Demonstrates keyboard navigation by highlighting the currently selected cell with a focus border showing once more the flexibility of the new cell navigation support
Snippet034CellEditorPerRowNewAPI - Demonstrates different CellEditor-Types in one COLUMN with 3.3-API of JFace-Viewers
After digging through the code, I found the following method in the ColumnViewer class:
/**
* Hook up the editing support. Subclasses may override.
*
* #param control
* the control you want to hook on
*/
protected void hookEditingSupport(Control control) {
// Needed for backwards comp with AbstractTreeViewer and TableTreeViewer
// who are not hooked this way others may already overwrite and provide
// their
// own impl
if (viewerEditor != null) {
control.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
// Workaround for bug 185817
if (e.count != 2) {
handleMouseDown(e);
}
}
public void mouseDoubleClick(MouseEvent e) {
handleMouseDown(e);
}
});
}
}
So, I overrode that function within my TableViewer subclass:
#Override protected void hookEditingSupport(Control control) {
// We know there should be an editor avaiable
// if (viewerEditor != null) {
control.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
// Workaround for bug 185817
if (e.count != 2) {
// We don't want to edit on single clicks
// handleMouseDown(e);
}
}
public void mouseDoubleClick(MouseEvent e) {
// This method is private, so copy the implementation
// handleMouseDown(e);
ViewerCell cell = getCell(new Point(e.x, e.y));
e.count--; // A hack to make things work - pretend like it's a single click
if (cell != null) {
triggerEditorActivationEvent(new ColumnViewerEditorActivationEvent(
cell, e));
}
}
});
// }
}
This works for me. Tell me if it works for you.