In GWT how do I handle the tab click event? - gwt

I have a tab layout panel in my ui.xml :
<g:TabLayoutPanel ui:field="tabPanel" barHeight='30'>
<g:tab>
<g:header size='7'>tab1</g:header>
<g:SimplePanel ui:field="tab1" height="100%"/>
</g:tab>
<g:tab>
<g:header size='7'>tab2</g:header>
<g:SimplePanel ui:field="tab2" height="100%"/>
</g:tab>
</g:TabLayoutPanel>
how do I handle the event generated on clicking Tab2?

Handle the SelectionEvent<Integer> or BeforeSelectionEvent<Integer> depending on your requirements.
e.g:
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
#Override
public void onSelection(SelectionEvent<Integer> event) {
if (event.getSelectedItem() == 1) {
// Code
}
}
});
or:
#UiHandler("tabPanel")
void onTabSelection(SelectionEvent<Integer> event) {
if (event.getSelectedItem() == 1) {
// Code
}
}

Related

Xamarin Layout can't receive focus

I'm trying to create a compound view component in Xamarin Forms called FormElement which is composed of two labels and an Entry:
<?xml version="1.0" encoding="UTF-8"?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:custom="clr-namespace:Mynamespace;assembly=Mynamespace"
x:Class="Mynamespace.Components.FormEntry">
<StackLayout Orientation="Horizontal">
<Label x:Name="formRequiredStar"
IsVisible="{Binding IsRequired}"
Text="*" TextColor="Red"
FontSize="15"
FontAttributes="Bold"
Margin="-12,0,0,0"
HorizontalOptions="Start" />
<Label x:Name="formLabel"
HorizontalOptions="Start"
Text="{Binding LabelText}"
TextColor="{Binding LabelTextColor}"
FontSize="{Binding LabelTextFontSize}"
FontAttributes="{Binding LabelTextFontStyle}" />
</StackLayout>
<Frame BorderColor="Black"
CornerRadius="7"
Padding="5,0"
Margin="0,-3,0,0"
HasShadow="false">
<Entry x:Name="mainEntry"
Keyboard="{Binding KeybdType}"
Placeholder="{Binding EntryPlaceHolder}"
TextColor="Black"
FontSize="Default"
HeightRequest="{Binding EntryHeight}" />
</Frame>
</StackLayout>
Next, I want to switch focus from the Entry to a "next" element when the user taps the DONE button, so I do:
namespace Mynamespace.Components
{
public partial class FormEntry : StackLayout
{
public VisualElement NextFocus
{
get { return (VisualElement)GetValue(NextFocusProperty); }
set { SetValue(NextFocusProperty, value); }
}
public static readonly BindableProperty NextFocusProperty =
BindableProperty.Create(nameof(NextFocus),
typeof(VisualElement),
typeof(FormEntry),
null,
Xamarin.Forms.BindingMode.OneWay);
public FormEntry()
{
InitializeComponent();
BindingContext = this;
mainEntry.Completed += (s, e) =>
{
if (NextFocus != null)
{
NextFocus.Focus();
}
};
}
}
}
Next, in order for a FormEntry to be the target of NextFocus, I tried adding
this.Focused += (s,e) => { mainEntry.Focus(); };
to the constructor, but the handler is never called, and I also tried overriding
public new void Focus() {
mainEntry.Focus();
}
but this method is never called. Layout classes are descended from VisualElement so they should inherit Focused. Is there something about Layout objects that I'm missing? I could understand that Layout objects aren't usually the target of focus, but the event handler is supposedly there so I ought to be able to use it.
Here's an example of how I utilize the FormEntry on a login screen:
<!-- Email -->
<controls:FormEntry x:Name="usernameEntry"
Margin="25,40,25,0"
IsRequired="true"
EntryHeight="40"
KeybdType="Email"
NextFocus="{x:Reference passwordEntry}"
LabelText="{il8n:Translate Emailorusername}"
EntryPlaceHolder="{il8n:Translate EnterUsername}">
</controls:FormEntry>
<!-- Password -->
<controls:FormEntry x:Name="passwordEntry"
Margin="25,0,25,0"
IsRequired="true"
EntryHeight="40"
LabelText="{il8n:Translate Password}"
EntryPlaceHolder="{il8n:Translate EnterPassword}" />
I think you have get the nextfocus element, you can get mainEntry from nextfocus, like this:
public FormEntry ()
{
InitializeComponent ();
BindingContext = this;
mainEntry.Completed += (s, e) =>
{
if (NextFocus != null)
{
FormEntry formentry = (FormEntry)NextFocus;
Entry entry = formentry.mainEntry;
entry.Focus();
}
};
}
Then you can find you will get focus.

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 filter one combobox value based on another combobox value in zk?

I have a list with two Combo boxes. I have some values in Combo box 1 and Combo box 2. While choose item in Combo box 1, the values will be filtered in Combo box 2 and rendered in UI.
Please someone help with this.
There is a nice example on zk fiddle in MVVM on how you could do this.
You can find it here.
If link dies, here is the code :
Zul :
<zk>
<window border="normal" title="Dependent components" apply="org.zkoss.bind.BindComposer"
viewModel="#id('vm') #init('pkg$.DependencyViewModel')">
<checkbox checked="#bind(vm.infoFromComboboxesRequired)" label="require comboboxes ?"
onCheck="#command('flagChecked')"/>
<combobox model="#load(vm.comboModel1)" visible="#load(vm.infoFromComboboxesRequired)"
selectedItem="#bind(vm.comboValue1)" onSelect="#command('combo1Selected')">
<template name="model">
<comboitem label="#load(each)" value="#load(each)"/>
</template>
</combobox>
<combobox model="#load(vm.comboModel2)" visible="#load(vm.infoFromComboboxesRequired)"
selectedItem="#bind(vm.comboValue2)" onSelect="#command('combo2Selected')">
<template name="model">
<comboitem label="#load(each)" value="#load(each)"/>
</template>
</combobox>
</window>
</zk>
Viewmodel:
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
public class DependencyViewModel {
boolean infoFromComboboxesRequired = false;
ListModelList<String> comboModel1;
ListModelList<String> comboModel2;
String comboValue1;
String comboValue2;
#Init
public void init() {
comboModel1 = new ListModelList<String>();
comboModel2 = new ListModelList<String>();
}
#Command("flagChecked")
#NotifyChange({"comboModel1", "comboModel2"})
public void onFlagChecked() {
comboModel1.clear();
comboModel2.clear();
comboValue1 = null;
}
#Command("combo1Selected")
#NotifyChange("comboModel2")
public void onCombo1Selected() {
comboModel2.clear();
}
#Command("combo2Selected")
#NotifyChange("comboModel2")
public void onCombo2Selected() {
Clients.showNotification("selected combo 2 : " + comboValue2);
}
public ListModel<String> getComboModel1() {
if(infoFromComboboxesRequired) {
comboModel1.add("aaaa");
comboModel1.add("bbbb");
comboModel1.add("cccc");
comboModel1.add("dddd");
comboModel1.add("eeee");
}
return comboModel1;
}
public ListModel<String> getComboModel2() {
if(infoFromComboboxesRequired && comboValue1 != null) {
comboModel2.add(this.comboValue1 + "1111");
comboModel2.add(this.comboValue1 + "2222");
comboModel2.add(this.comboValue1 + "3333");
comboModel2.add(this.comboValue1 + "4444");
comboModel2.add(this.comboValue1 + "5555");
}
return comboModel2;
}
public boolean isInfoFromComboboxesRequired() {
return infoFromComboboxesRequired;
}
public void setInfoFromComboboxesRequired(boolean infoFromComboboxesRequired) {
this.infoFromComboboxesRequired = infoFromComboboxesRequired;
}
public String getComboValue1() {
return comboValue1;
}
public void setComboValue1(String comboValue1) {
this.comboValue1 = comboValue1;
}
public String getComboValue2() {
return comboValue2;
}
public void setComboValue2(String comboValue2) {
this.comboValue2 = comboValue2;
}
}

How to add form elements in gwt-bootstrap3

I am trying to add some elements in gwt-bootstrap3 modal [link], I am using UI-binder to generate the screen but nothing is appear.
my ui binder class
<?xml version="1.0" encoding="UTF-8"?>
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder' xmlns:g='urn:import:com.google.gwt.user.client.ui' xmlns:b='urn:import:org.gwtbootstrap3.client.ui'
xmlns:res="urn:with:com.db.cary.client.resources.CSSResources">
<ui:with type="com.db.cary.client.resources.CSSResources" field="res">
</ui:with>
<b:Modal closable="true" fade="true" dataBackdrop="TRUE" dataKeyboard="true">
<b:ModalBody>
<b:Form type="HORIZONTAL">
<b:FieldSet>
<b:Legend>Please enter the book detail</b:Legend>
<b:FormGroup>
<b:FormLabel for="bookTitle" addStyleNames="col-lg-2">Title</b:FormLabel>
<g:FlowPanel addStyleNames="col-lg-10">
<b:TextBox placeholder="Enter book Title" ui:field="titleTextBox" />
</g:FlowPanel>
</b:FormGroup>
<b:FormGroup>
<b:FormLabel for="bookAuthor" addStyleNames="col-lg-2">Author</b:FormLabel>
<g:FlowPanel addStyleNames="col-lg-10">
<b:ListBox ui:field="authorListBox" />
<b:Button ui:field="newAuthorButton" type="LINK" size="EXTRA_SMALL">New author</b:Button>
</g:FlowPanel>
<g:FlowPanel addStyleNames="col-lg-offset-2 col-lg-10">
<b:TextBox ui:field="authorTextBox" placeholder="enter slash (/) separated list of authors"></b:TextBox>
</g:FlowPanel>
</b:FormGroup>
<b:FormGroup>
<b:FormLabel for="bookCategory" addStyleNames="col-lg-2">Category</b:FormLabel>
<g:FlowPanel addStyleNames="col-lg-10">
<b:ListBox ui:field="categoryListBox" />
<b:Button ui:field="newCategoryButton" type="LINK" size="EXTRA_SMALL">New Category</b:Button>
</g:FlowPanel>
<g:FlowPanel addStyleNames="col-lg-offset-2 col-lg-10">
<b:TextBox ui:field="categoryTextBox" placeholder="enter category"></b:TextBox>
</g:FlowPanel>
</b:FormGroup>
</b:FieldSet>
</b:Form>
</b:ModalBody>
<b:ModalFooter>
<b:Button type="PRIMARY" ui:field='submitButton'>Submit</b:Button>
<b:Button ui:field='cancelButton'>Cancel</b:Button>
</b:ModalFooter>
</b:Modal>
</ui:UiBinder>
and my view class
public class AddBook extends Modal {
interface CheckOutPopUpBinder extends UiBinder<Widget, AddBook> {
}
private static final CheckOutPopUpBinder binder = GWT.create(CheckOutPopUpBinder.class);
private final AuthorAndCategoryServiceAsync authorService = GWT.create(AuthorAndCategoryService.class);
private final LibraryServiceAsync libraryServiceAsync = GWT.create(LibraryService.class);
#UiField
TextBox titleTextBox;
#UiField
ListBox authorListBox;
#UiField
TextBox authorTextBox;
#UiField
ListBox categoryListBox;
#UiField
Button submitButton;
#UiField
Button cancelButton;
#UiField
Button newAuthorButton;
#UiField
Button newCategoryButton;
#UiField
TextBox categoryTextBox;
public AddBook(String title) {
binder.createAndBindUi(this);
setTitle(title);
initializeAuthorListBox();
initializeCategoryListBox();
}
private void initializeCategoryListBox() {
authorService.getCategories(null, new AsyncCallback<List<CategoryDTO>>() {
#Override
public void onFailure(Throwable arg0) {
Window.alert("unable to fetch category list");
}
#Override
public void onSuccess(List<CategoryDTO> arg0) {
for (CategoryDTO category : arg0)
categoryListBox.addItem(category.getCategoryName());
}
});
categoryListBox.setMultipleSelect(false);
categoryTextBox.setVisible(false);
}
private void initializeAuthorListBox() {
authorService.getAuthors(null, new AsyncCallback<List<AuthorDTO>>() {
#Override
public void onSuccess(List<AuthorDTO> arg0) {
for (AuthorDTO author : arg0) {
authorListBox.addItem(author.getAuthorName());
}
}
#Override
public void onFailure(Throwable arg0) {
Window.alert("Unable to fetch the list of authors");
}
});
authorListBox.setMultipleSelect(true);
authorTextBox.setVisible(false);
}
#UiHandler("cancelButton")
public void cancelAction(ClickEvent e) {
AddBook.this.hide();
}
#UiHandler("submitButton")
public void submitAction(ClickEvent e) {
AddBookDTO bookDTO = new AddBookDTO();
String bookTitle = titleTextBox.getText();
String bookCategory = categoryListBox.getSelectedValue() == null ? categoryTextBox.getText() : categoryListBox.getSelectedValue();
List<String> authorsList = new ArrayList<String>();
for (int i = 0; i < authorListBox.getItemCount(); i++) {
if (authorListBox.isItemSelected(i)) {
authorsList.add(authorListBox.getItemText(i));
}
}
if (null != authorTextBox.getText() && authorTextBox.getText().trim().length() > 0) {
String[] values = authorTextBox.getText().split("/");
for (String str : values) {
authorsList.add(str);
}
}
if (bookTitle == null || bookTitle.length() <= 0) {
Window.alert("Please enter a valid book title");
return;
} else if (bookCategory == null || bookCategory.length() <= 0) {
Window.alert("Please enter a valid book category");
return;
} else if (authorsList == null || authorsList.size() == 0) {
Window.alert("Please enter valid authors");
return;
}
bookDTO.setBookTitle(bookTitle);
bookDTO.setCategroyName(bookCategory);
bookDTO.setAuthors(authorsList);
libraryServiceAsync.addBook(bookDTO, new AsyncCallback<Boolean>() {
#Override
public void onFailure(Throwable arg0) {
Window.alert("There is some issue with database while adding book, Please contact your admin");
}
#Override
public void onSuccess(Boolean arg0) {
Window.alert("Book is successfully added !!!");
}
});
this.hide();
}
#UiHandler("newAuthorButton")
public void addAuthor(ClickEvent e) {
authorTextBox.setVisible(true);
}
#UiHandler("newCategoryButton")
public void addCategory(ClickEvent e) {
categoryTextBox.setVisible(true);
}
}
I am not sure, What is wrong but only header is appearing in the modal.
You are calling AddBook.this.show(); - this shows the Modal that is the base of this AddBook instance, not the instance defined in your UiBinder template. When you call setTitle(title); you are setting the header/title on this instance - this is why all you see is the header and not the rest of the modal. You should assign an ui:field to your Modal defined in your UiBinder template and show/hide it.
Also AddBook shouldn't be extending Modal - it shouldn't extend any widget class at all :) Normally, UiBinder classes are extending Composite - because your UiBinder template is composed of a variety of widgets and Composite is used to bring them together without exposing any of their APIs: you call initWidget with the result of binder.createAndBindUi(this).
But if you are creating a widget whose "main" widget is Modal, like here, you should just call binder.createAndBindUi(this) and ignore the Widget that is returned (just like you are doing now). This is because Modal attaches itself to the DOM, bypassing any GWT mechanism (actually, it conflicts with it).

GWT Button EventListener not fired

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() {...});