GWT adding a ClickHandler to a DOM element - gwt

lets say i have a custom widget which has a ClickHandler. Here's the example:
public class TestWidget extends Composite {
private static TestWidgetUiBinder uiBinder = GWT
.create(TestWidgetUiBinder.class);
interface TestWidgetUiBinder extends UiBinder<Widget, TestWidget> {
}
#UiField
Button button;
public TestWidget(String firstName) {
initWidget(uiBinder.createAndBindUi(this));
button.setText(firstName);
}
#UiHandler("button")
void onClick(ClickEvent e) {
Window.alert("Hello!");
}
}
When i try to add this Widget like this:
TestWidget testWidget = new TestWidget("myTestWidget");
RootPanel.get().add(testWidget);
everything is fine. If i click on my button i get the message i expect.
However if i add it like this:
TestWidget testWidget = new TestWidget("myTestWidget");
RootPanel.getBodyElement().appendChild(testWidget.getElement());
my click event is not being fired. I'm struggeling to understand why.
It would be nice if someone could explain this to me or link me to an resource where i can read this up. Finally i would like to know if it is possible to add the clickhandler afterwards i appended the child event and if that way is recommended. Thanks it advance for help.
kuku

When you call add(), Widget.onAttach() is called on the widget that is being added to the panel. onAttach does some work to register the widget to receive events. appendChild() simply attaches one DOM element to another and does nothing else. You should be able to get events working in the second case by doing this:
Element element = testWidget.getElement();
RootPanel.getBodyElement().appendChild(element);
DOM.sinkEvents(element,
Event.getTypeInt(ClickEvent.getType().getName())
| DOM.getEventsSunk(element);
However, I haven't tested this and I wouldn't recommend that you use it in a real application. Using add() is definitely preferred, using appendChild() in this way has no advantages and may lead to unexpected behaviour.

Related

GWT 2.4 customized ListBox doesn't fire Change event

I have added some extra functionality to the standard GWT ListBox by extending it like so:
public class FeatureListBox extends ListBox
{
public FeatureListBox()
{
}
public FeatureListBox(boolean isMultipleSelect)
{
super(isMultipleSelect);
}
public FeatureListBox(Element element)
{
super(element);
}
}
Nothing fancy here. However, the Change event is not firing now, or at least the handler (attached per below) is not getting invoked.
FeatureListBox listBox = new FeatureListBox();
listBox.addChangeHandler(new ChangeHandler()
{
public void onChange(ChangeEvent event)
{
// Do something here...
}
});
Any ideas why?
Either remove the no-argument constructor from FeatureListBox or call super() inside it, otherwise the initialization in the superclasses won't happen, which would probably result in what you're seeing.
The problem was in the way I was using my custom list box. In my application I wrap GWT Widgets around existing DOM elements on the page using the static wrap() methods of their widget classes in which the widgets get marked as attached, making them fire events. I didn't do that with my custom list box class originally, so I ended up implementing a static wrap() method similar to the one of the regular ListBox widget and using it in my code. Everything works like a charm now.

How to hide suggestions in GWT SuggestBox?

I am using GWT 2.4. I have a Suggestbox and I have a requirement to hide the suggestion list under certain cases. The context is as below.
After user selects a suggestion from suggestion list, I am populating two other text box fields, with values corresponding to the selection. For example, suppose the suggestbox contains user-names, and user selects a user-name from suggestions, then other two fields, say user address and email are populated in two other text boxes. These two fields are read only now. Then user clicks on an 'Edit' button. Now the user can edit either user- name ( ie edit in suggestion box), user address and email. It doesn't make sense to show the suggestions again when the user is editing the user-name, since the user has already selected the user and decided to edit it. In a nutshell my SuggesBox should behave as a normal text box. I tried following code, (I know hideSuggestionList() is deprecated) but its not working.
display.getSuggestBox().hideSuggestionList();
Reading the javadoc for hideSuggestionList() it is said that, "Deprecated. use DefaultSuggestionDisplay.hideSuggestions() instead". I don't know how to use DefaultSuggestionDisplay, and I'm using SuggestBox with 'MultiWordSuggestOracle'.
Thanks for helping me out!!
What you can do is simply swap the SuggestionBox with a normal TextBox when the user clicks edit and back when edit is closed. Also because if you would hide the suggestions list, it still queried from the server. By swapping the widget you don't have to care about side effects. SuggestionBox itself uses also a TextBox and thus for the user it's not visible the widget has changed.
If you don't use your own SuggestionDisplay, then this should Just Work™:
((DefaultSuggestionDisplay) suggestBox.getSuggestionDisplay()).hideSuggestions();
Here is the Solution
My Entry Point Class
public class SuggestionEntryPoint implements EntryPoint {
#Override
public void onModuleLoad() {
SuggestBoxWidget suggestBoxWidget = new SuggestBoxWidget();
RootPanel rootPanel = RootPanel.get();
suggestBoxWidget.createOracle();
suggestBoxWidget.createWidgetAndShow(rootPanel);
rootPanel.add(suggestBoxWidget);
DOM.getElementById("loader").removeFromParent();
}
}
And here is my Widget
public class SuggestBoxWidget extends Composite {
private TextBox textSuggestBox = new TextBox();
private SuggestBox suggestBox = null;
DefaultSuggestionDisplay suggestionDisplay = new DefaultSuggestionDisplay();
MultiWordSuggestOracle suggestOracle = new MultiWordSuggestOracle();
private static SuggestBoxWidgetUiBinder uiBinder = GWT
.create(SuggestBoxWidgetUiBinder.class);
interface SuggestBoxWidgetUiBinder extends
UiBinder<Widget, SuggestBoxWidget> {
}
public SuggestBoxWidget() {
initWidget(uiBinder.createAndBindUi(this));
}
public void registerEvents(){
suggestBox.addKeyUpHandler(new KeyUpHandler() {
#Override
public void onKeyUp(KeyUpEvent event) {
if(suggestBox.getText().equalsIgnoreCase("1")){
suggestionDisplay.hideSuggestions();
}
}
});
}
public void createWidgetAndShow(HasWidgets container){
suggestBox = new SuggestBox(suggestOracle,textSuggestBox,suggestionDisplay);
container.clear();
container.add(suggestBox);
registerEvents();
}
public void createOracle(){
for(int i=1;i<=100;i++){
suggestOracle.add(i+"");
}
}
}
Actually you have to create a SuggestBox with 3 Parameters to the Constructor.

How to instantiate an Event Handler interface in GWT using uiBinder?

I'm trying to use a custom widget: gwtupload with it's custom handlers. The handlers are defined as interfaces, as in, Interface.OnCustomEventHandler and the method, according to the API, that I want to use is like this code, but I'm not sure how to implement this with uiBinder.:
void onCustomEvent (Interface interface)
Normally for uiBinder I use this code for the regular gwt widgets:
#Widget widget;
#UiHandler("widget")
void onClick(ClickEvent event){
//Handle the event processing here.
}
Presently, when I try this,
#UiHandler("widget")
void onCustomEvent(ICustomInterface customInterface){
...
I get this null pointer exception:
[ERROR] Generator 'com.google.gwt.uibinder.rebind.UiBinderGenerator' threw an exception while rebinding '...ViewImpl.ViewImplUiBinder'
java.lang.NullPointerException
Here is the new code I tried:
public class MUpld extends Composite {
private static MUpldUiBinder uiBinder = GWT.create(MUpldUiBinder.class);
interface MUpldUiBinder extends UiBinder<Widget, MUpld> {
}
#UiField MultiUploader uploader;
public MUpld() {
final IUploader.OnFinishUploaderHandler onFinishUploaderHandler = new IUploader.OnFinishUploaderHandler() {
#Override
public void onFinish(IUploader iUploader) {
if (uploader.getStatus() == Status.SUCCESS){
System.out.println("In the onFinish method!");
}
}
};
initWidget(uiBinder.createAndBindUi(this));
uploader.addOnFinishUploadHandler(onFinishUploaderHandler);
}
}
In the debugger, I saw the handler get attached to the uploader widget I defined, but then the current uploader became a different one once the code moved out of this class. I tried using the final modifier, as that is the only way I know to get a variable into an inner class, but gwt would complain with:
[ERROR] com.cdg.complexityCalculator.client.view.MUpld has no default (zero args) constructor.
To fix this, you can define a #UiFactory method on the UiBinder's owner, or annotate a constructor of MUpld with #UiConstructor.
I wasn't able to get either of those options to work, but I realized I had the last two lines of code switched, so I changed it to what I have now and the handler loaded up with the correct object.
Any ideas as to how to get this to work? Everything else is in place, I just need a way to capture this event after my servlet has finished processing.
When I changed the last two lines of code, the handler got loaded properly. Now the objects are being created with the handler binding to the correct object.
initWidget(uiBinder.createAndBindUi(this));
uploader.addOnFinishUploadHandler(onFinishUploaderHandler);
I had to wait until the uiBinder created the instance of the uploader widget, then I was able to add the handler to it.
One of the tricks I've learned is to add a handler in the constructor for a composite widget you create, that way it's more of an encapsulated component. It handles it's own events.

Add SuggestBox to CellTable as an editable cell

Is there any way to SuggestBox to CellTable? Maybe there is another solution then SuggestBox?
I need to get an editable cell with suggestion feature?
I'm using GWT 2.4.
I don't think you can add it directly in. Try using a ClickableTextCell as the cell for that column. Then code your ValueUpdater (which will be called when the cell is clicked) to open up a DialogBox. Put your SuggestBox, and other widgets (OK button, Cancel button, and such), inside that DialogBox. Initialize the SelectionBox with the current contents of the cell. The DialogBox will likely be a DialogBox subclass with extra state data you initialize with the object for that CellTable row as well as the field for that column, so that the OK action knows what field on what object to update with the new contents of the SuggestBox. Essentially it's a popup editor. Not ideal, because users will expect the editor to be embedded in the CellTable, but there are only a few cell editors available (EditTextCell, DatePickerCell, SelectionCell and CheckboxCell, and maybe another variant of text editing), but I've used this technique, and really, it's not too bad.
I ended up using FlexTable instead of CellTable. With FlexTable you may put any widget inside a table cell.
I needed this also and found a solution (under testing, but solong it is working):
I copied the Code from TextInputCell into a new Class SuggestBoxTextInputCell
public class SuggestBoxTextInputCell extends AbstractInputCell<String, SuggestBoxTextInputCell.ViewData> {
MySuggestBox suggestBox;
and added some lines to the onBrowserEvent method:
// Ignore events that don't target the input.
InputElement input = getInputElement(parent);
String eventType = event.getType();
if (BrowserEvents.FOCUS.equals(eventType)) {
TextBox textBox = new MyTextBox(input);
suggestBox = new MySuggestBox(getSuggestOracle(), textBox);
suggestBox.onAttach();
}
Element target = event.getEventTarget().cast();
The classes MySuggestBox and MyTextbox exist only to make the needed constructor and methods public:
private class MyTextBox extends TextBox {
public MyTextBox(Element element) {
super(element);
}
}
private class MySuggestBox extends SuggestBox {
public MySuggestBox(SuggestOracle suggestOracle, TextBox textBox) {
super(suggestOracle, textBox);
}
#Override
public void onAttach() {
super.onAttach();
}
}
getSuggestOracle() only delivers the needed SuggestOracle. Hope someone can use this solution.
I needed this as a solution so I play around with the solution provided by Ande Hofer.
The exact same issue met by Ankit Singla, when the suggestbox is working fine when I press "Enter" key, but not from the "Mouse Click".
I go on further and add-on this onto the solution.
if (BrowserEvents.FOCUS.equals(eventType)) {
...
...
suggestbox.addSelectionHandler(new SelectionHandler<Suggestion>() {
#Override
public void onSelection(SelectionEvent<Suggestion> event) {
Suggestion selectedSuggestion = event.getSelectedItem();
String selectedValue = selectedSuggestion.getReplacementString();
onSuggestSelected(input, selectedValue, valueUpdater);
}
});
suggestbox.onAttach();
}
and a private function
private void onSuggestSelected(Element input, String value,
ValueUpdater<String> valueUpdater) {
input.blur();
suggestbox.onDetach();
if (suggestbox.getSuggestionDisplay().isSuggestionListShowing()) {
((DefaultSuggestionDisplay) suggestbox.getSuggestionDisplay()).hideSuggestions();
}
valueUpdater.update(value);
}
So far so good.

GWT - Avoid to listen to events

I'm using SliderBar widget from Google Web Toolkit Incubator. By default, this widget listens to some keyboard events, e.g. left arrow. I'd like to know if there's a way to avoid the widget listens to those events.
I'm using UiBinder and tried to use the function unsinkEvents but nothing happens. Here's the snippet of code:
#UiField(provided = true)
SliderBar slbRotate;
public NewViewImpl() {
slbRotate = new SliderBar(-180,180);
slbRotate.setStepSize(10);
slbRotate.setCurrentValue(0);
slbRotate.setWidth("478px");
slbRotate.setHeight("22px");
slbRotate.unsinkEvents(Event.KEYEVENTS);
initWidget(binder.createAndBindUi(this));
}
I also used KeyCodes.KEY_LEFT in the argument of the unsinkEvents function, but doesn't work either.
Thanks.
With the
unsinkEvents
function.
I created a short example to show the basics:
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.TextBox;
public class ExtendedTextBox extends TextBox {
public ExtendedTextBox() {
sinkEvents(Event.KEYEVENTS);
}
#Override
public void onBrowserEvent(Event event) {
Window.alert("keypress");
}
public void unSinkKeyEvent(){
unsinkEvents(Event.KEYEVENTS);
}
}
This example creates a TextBox and whenever you press a key two MessageBoxes (one for the keydown one for the keyup) pop up. If you call the unSinkKeyEvent function this behafios stops.
So if you don't want to have speciffic behavior on SliderBar widget you just have too call the unsinkEvents function an specify the event you don't want to have (just look at the help)
Regards,
Stefan