GWT Button EventListener not fired - gwt

I have a <div id="test"><input type="button" value="OK" /></div> html tag.
I used:
((HasClickHandlers)RootPanel.get("test").getWidget(0)).addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.alert('sss');
}
}
I executed but no action.
Update:
package com.example.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.*;
import com.google.gwt.user.client.ui.RootPanel;
public class ExampleWebApp implements EntryPoint {
public void onModuleLoad() {
((HasClickHandlers) RootPanel.get("test").getWidget(0)).addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.alert("i got it");
}
});
}
}
HTML:
<table>
<tr>
<div id="test">
<input type=button onClick="" value='click here'>
</div>
</tr>
</table>

The GWT Button widget is a button tag and not a input tag. Which means you can't use the GWT Button widget in this case. To make it work you need to create your own widget, which can be based on the widget ButtonBase, but needs to be initialized with an InputElement object instead of a ButtonElement.
The next step to get tag from html is to add something similar to the static wrap method present in most widgets. Here is how it would be used in your example when the input would have been a button tag:
Button.wrap(RootPanel.get("test").getWidget(0).getElement()).addClickHandler(
new ClickHandler() {
#Override public void onClick(ClickEvent event) {
Window.alert('sss');
}
});
In you case you could add a wrap method to your custom input widget. See the Button widget implementation of te wrap method, it's the same, expect of course for the creation of the widget itself.

You can't just take an html button and try to add click handlers to it. You need to create the button using gwt code. Try:
<div id="test"></div>
And then:
Button button = new Button("OK");
RootPanel.get("test").add(button);
button.addClickHandler(new ClickHandler() {...});

Related

Wicket get button component text

I would like to get the text of a button submitProceed and will use it in my code/logic.
HTML
<button wicket:id="submitProceed" type="button" class="btn btn-sm btn-primary btn-save" disabled="disabled">Submit</button>
Is it possible to get the button text Submit? Also, how to I change this to Proceed?
This is how I initialize my button component:
private Component m_btnSubmit;
...
private Component createForm() {
Form<Void> result = new Form<>("form");
...
result.add(m_btnSubmit = createSubmit("submit"));
...
return result;
}
private Component createSubmit(String wicketId) {
AjaxButton result = new AjaxButton(wicketId) {
private static final long serialVersionUID = 1L;
#Override
protected void onConfigure() {
super.onConfigure();
...
setOutputMarkupId(true);
}
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
...
}
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
// TODO: Get button text here
// Check button text if either `Submit` or `Proceed`
// Action depending on button text (Also change button text)
}
#Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
super.onError(target, form);
...
}
};
...
return result;
}
Solution:
First of All, I would like to thank #Andrea and #martin for their solution, I just tweak it a bit for fit my existing code.
Since I need a span containing the text Submit and later be changed to Proceed... I need to add a span inside button tag like this:
<button wicket:id="submit" type="button"><span wicket:id="labelSubmit">Submit</span&lg;</button>
the problem with this, I am getting an error that seems it would not allow button to have a nested component.
Error is something like this:
org.apache.wicket.markup.MarkupException: Expected close tag for '<button wicket:id="submit" type="button">' Possible attempt to embed component(s) '<span wicket:id="labelSubmit">' in the body of this component which discards its body.
To fix this, I need to change from button to a so it would look like this:
<a wicket:id="submit" type="submit"><span wicket:id="labelSubmit">Submit</span&lg;</a>
...
IModel m_labelModel = Model.of("Submit");
Label m_labelSubmit = new Label("labelSubmit", m_labelModel);
m_labelSubmit.setOutputMarkupId(true);
...
In my button's onSubmit:
m_labelModel.setObject("Proceed");
target.add(this);
Note that I only did change m_labelModel, but I need to add the current button (this) so that the change will reflect in the UI.
For those, having the same issue or setup... hope this helps :)
If you use new AjaxButton(String, IModel) constructor, as Andrea Del Bene suggested, then the model will be used to set the value attribute of the button:
<button value="Submit"></button>
If you need to manipulate the textContent of the <button>, i.e. <button>!!!THIS!!!</button> then you can add a Label component as a child:
IModel<String> labelModel = Model.of("Submit");
Label label = new Label("labelId", labelModel);
label.setOutputMarkupId(true);
button.add(label);
...
In AjaxButton#onSubmit(AjaxRequestTarget target) you can update it:
labelModel.setObject("New value");
target.add(label);
you should use button's constructor that takes also a model as button's label:
IModel labelModel = Model.of("Submit");
new Button<>("submit", labelModel);
Than you can use the model to get/set this value

GWT Polymer UiBinder Vaadin Elements addEventListener Event KeysPressedEvent

I'm trying to follow the basic hello world examples that use GWT Polymer with the UiBinder Elements.
The basic GWT example stub generated code handles the key to specify input.
I thought it would be easy to have an event handler and check the key that was pressed.
I'm probably doing something very basic wrong.
Maybe some import I'm not doing or Polymer.importHref I forgot to include.
The event does trigger but I get undefined when I attempt to get the key from the event.
I guessed using "keypress" as the other examples use "click" and it did trigger but what is the right type to use?
I outputed some of the values and get the following:
event.getDetail().getKey() -> undefined
event.toString() -> [object KeyboardEvent]
nameFieldInput.getValue() ->
nameFieldInput.getInnerHTML() -> show what was typed before processing the current key
I also need to know what the string value or Constant to use for the key to do the test.
Please advise how to make this work using the event listener.
Here is my current code:
Main.ui.xml file
<paper-fab ui:field="sendButton" icon="gavel" title="send rpc" class="sendrpc" />
<paper-dialog ui:field="sendMsgDialog" entry-animation="fade-in-animation"
class="dialog" modal="">
<h2>Send RPC to Server</h2>
<paper-input ui:field="nameFieldInput" label="Please enter your name:"
required="" auto-validate="" pattern="[a-zA-Z]*"
minlength="4" char-counter="" error-message="required input!"/>
<div class="buttons">
<paper-button dialog-dismiss="">Cancel</paper-button>
<paper-button ui:field="sendFieldButton"
dialog-confirm="">Send</paper-button>
</div>
</paper-dialog>
Main.java class
#UiField PaperInputElement nameFieldInput;
...
nameFieldInput.addEventListener("keypress", new EventListener<KeysPressedEvent>() {
public void handleEvent(KeysPressedEvent event) {
if (event.getDetail().getKey() == "enter" && event.getDetail().getCtrl() == false) {
sendMsgDialog.close();
sendNameToServer();
}
}
});
I used the two following examples documents to get to this point and they show the following examples of using the listener. Unfortunately the gwtproject example only uses the event trigger and does not use the event object information..
http://www.gwtproject.org/doc/latest/polymer-tutorial/elements-applogic.html
...
#UiField PaperFabElement addButton;
...
public Main() {
initWidget(ourUiBinder.createAndBindUi(this));
addButton.addEventListener("click", new EventListener() {
#Override
public void handleEvent(Event event) {
addItemDialog.open();
}
});
}
http://vaadin.github.io/gwt-polymer-elements/demo/#gwt/UiBinderElement
...
#UiField PaperTabsElement paperTabs;
...
paperTabs.addEventListener(IronSelectEvent.NAME, new EventListener<IronSelectEvent>() {
public void handleEvent(IronSelectEvent event) {
PaperTabElement tab = (PaperTabElement)event.getDetail().getItem();
toast.close();
toast.setText("Tab \"" + tab.getTextContent() + "\" has been selected");
toast.open();
}
});
Here is an example that uses GWT standard Ui instead of polymer from:
h2g2java.blessedgeek.com/2010/02/tutorial-gwt-rpc-stub-modified-with.html
z.ui.xml file
<g:HorizontalPanel ui:field="hPanel">
<g:Button ui:field="sendButton" text="Send"
styleName="{style.sendButton}" />
<g:TextBox ui:field="nameField" text="GWT User" />
</g:HorizontalPanel>
z.java file
#UiField
HorizontalPanel hPanel;
#UiField
Button sendButton;
#UiField
TextBox nameField;
//Fired when user clicks send Button
#UiHandler("sendButton")
public void sendOnClick(ClickEvent event){
sendNameToServer();
}
//Fired when user types in the nameField.
#UiHandler("nameField")
public void nameOnKeyUp(KeyUpEvent event){
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
sendNameToServer();
}
}
What about this:
nameFieldInput.getPolymerElement().addEventListener("keyup", new EventListener() {
#Override
public void handleEvent(Event e) {
NativeEvent ne = (NativeEvent)e;
if (ne.getKeyCode() == KeyCodes.KEY_ENTER && !ne.getCtrlKey()) {
sendMsgDialog.close();
sendNameToServer();
}
}
});
With the help of #Euclides answer I was able to fix the code and get it working.
Here is the working corrected version.
Main.java class
sendButton.addEventListener("click", new EventListener() {
public void handleEvent(Event event) {
sendMsgDialog.open();
nameFieldInput.setAutofocus(true);
}
});
...
nameFieldInput.addEventListener("keyup", new EventListener<KeysPressedEvent>() {
public void handleEvent(KeysPressedEvent event) {
NativeEvent nativeEvent = (NativeEvent)event;
// CharCode is blank unless you use "keypress" as the event
// nameFieldInput.setErrorMessage(nativeEvent.getCharCode()+":"+nativeEvent.getKeyCode()+":"+nativeEvent.getAltKey()+":"+nativeEvent.getCtrlKey()+":"+nativeEvent.getMetaKey()+":"+nativeEvent.getShiftKey());
if (nativeEvent.getKeyCode() == KeyCodes.KEY_ENTER
&& !nativeEvent.getAltKey() && !nativeEvent.getCtrlKey()
&& !nativeEvent.getMetaKey() && !nativeEvent.getShiftKey()) {
sendMsgDialog.close();
sendNameToServer();
}
}
});

How to add back the "loading" Element after removed it from Parent?

Ok, in war/MyProject.html, I have:
<body>
<div id="loading">
<div id="waitingForLoading"></div>
<BR/>
<img src="../images/loading.gif" />
</div>
...
</body>
in MyProject.java
public class OfflineMatching implements EntryPoint {
#Override
public void onModuleLoad() {
// this code works fine
if(DOM.getElementById("loading")!=null){
DOM.getElementById("loading").removeFromParent();
}
Button myButton=new Button("Enter Main Page");
RootPanel.get().add(myButton);
myButton.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
// this code does not work
if(DOM.getElementById("loading")==null){
DOM.appendChild(RootPanel.getBodyElement(), DOM.createElement("loading"));
}
}
});
}
}
So, did i do anything wrong?
Why this code does not work?
// this code does not work
if(DOM.getElementById("loading")==null){
DOM.appendChild(RootPanel.getBodyElement(), DOM.createElement("loading"));
}
DOM.createElement(String tagName) creates a <tagname> element. So, if you pass "loading" to it, it will create a <loading> element.
For a quick workaround, you can use RootPanel.get, and then call setVisible on the widget:
// onModuleLoad:
RootPanel.get("loading").setVisible(false);
// onClick:
RootPanel.get("loading").setVisible(true);
But a better approach would be creating the loading <div> as a widget in GWT and just call setVisible on its instance, without relying on ids.

GWT Bootstrap Modal buttons won't work with ClickHandler's onClick

I'm trying to create a dialog box using GWT-Bootstrap modal widget.
I can get it to display but have not been able to get the buttons to recognize events.
The cancel button onClick never fires.
Had some other code to try to get the addClass button to do do something but stripped it out. If I can get the cancel button to do something (anything!) I should be in good shape.
I've also tried the java using addDomHandler and that didn't work either.
Here's the XML:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:a="urn:import:cgs.common.client.gwt.bootstrap"
xmlns:b="urn:import:com.github.gwtbootstrap.client.ui"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<b:Modal title="Add Class?" ui:field="addClassModal" backdrop="STATIC" keyboard="true" animation="true">
<a:BootstrapField label="Classname:">
<a:BootstrapTextInput
ui:field="classname"
placeholder="Classname" />
</a:BootstrapField>
<b:Button ui:field="addClass">Add Class</b:Button>
<b:Button ui:field="cancel">Cancel</b:Button>
</b:Modal>
</ui:UiBinder>
And here's the java:
package cgs.teacher.portal.client.view.impl.bootstrap;
import cgs.common.client.gwt.bootstrap.BootstrapTextInput;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.Modal;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
public class AddClassDialogViewImpl
extends Composite
{
interface AddClassDialogViewImplUiBinder extends UiBinder<Widget, AddClassDialogViewImpl>
{
}
private static AddClassDialogViewImplUiBinder uiBinder = GWT
.create(AddClassDialogViewImplUiBinder.class);
#UiField
Modal addClassModal;
#UiField
BootstrapTextInput classname;
#UiField
Button addClass;
#UiField
Button cancel;
public AddClassDialogViewImpl()
{
initWidget(uiBinder.createAndBindUi(this));
cancel.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
addClassModal.hide();
}
});
addClassModal.toggle(); //PS. Show gave error. Had to use toggle to show!
}
}
Thanks!
Another workaround which I have found is adding the Modal component to the RootPanel :
public AddClassDialogViewImpl() {
initWidget(uiBinder.createAndBindUi(this));
cancel.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
//hide the widget
addClassModal.hide();
// unless you want to keep this modal as a singleton, you need to remove it from the DOM
RootPanel.get().remove(AddClassDialogViewImpl.this);
}
});
//add the widget to the DOM
RootPanel.get().add(this);
// show the widget
addClassModal.show();
}

why this event (onclick) do not fire?

UI:
<div class="scroll" ui:field="mainContainer">
<ul ui:field="liContainer">
</ul>
</div>
code :
LIElement li = Document.get().createLIElement();
AnchorElement a = Document.get().createAnchorElement();
a.setAttribute("href", "#");
li.appendChild(a);
Image img = new Image(fsd.getImgUrl());
img.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.alert("Hello, again");
}
});
SpanElement span = Document.get().createSpanElement();
span.setInnerText(fsd.getName());
a.appendChild(img.getElement());
a.appendChild(span);
liContainer.appendChild(li);
Note:
#UiField
UListElement liContainer;
The Image must be added to a parent Widget. By attaching the image's element directly to the DOM, you wind up bypassing GWT`s event dispatch system.