GWT:how to get selected radio button's value - gwt

I am create dynamic number of radio buttons in my GWT
public void createTestList(ArrayList<Test> result){
for(int i =0 ; i<result.size();i++){
int id = result.get(i).getTestId();
RadioButton rd = new RadioButton("group", result.get(i).getTestType());
verticalPanel.add(rd);
}
where Test is my Entity class ..
I am getting 4 different types of radio buttons in my view , Now if i select any one of the radio button, first I need to get the id of the selected Radio button , how can this be possible ?
secondly How will i check that which one of the multiple radio button is selected ?
Thanks

You need to check public java.lang.Boolean getValue() on each radio button whether it is checked or not.

it is possible to add click handler and update selected radio button variable:
choiceItemKind = new VerticalPanel();
ArrayList<String> kinds = new ArrayList<String>();
kinds.add(...);
kinds.add(...);
choiceItemKind.clear();
ClickHandler choiceClickHandler = new ClickHandler()
{
#Override
public void onClick(ClickEvent event)
{
addItemKindSelectedLabel = ((RadioButton) event.getSource()).getText();
}
};
for (String label : kinds)
{
RadioButton radioButton = new RadioButton("kind", label);
//radioButton.setTitle("Tooltyp");
if (label.equals(addItemKindSelectedLabel))
radioButton.setValue(true);
radioButton.addClickHandler(choiceClickHandler);
choiceItemKind.add(radioButton);
}
...
addItemKindSelectedLabel = "";
...
if (!addItemKindSelectedLabel.isEmpty())
...;
upd: set selected radiobutton without rebuild:
for (int i = 0; i < choiceItemKind.getWidgetCount(); i++)
{
RadioButton radioButton = (RadioButton) choiceItemKind.getWidget(i);
radioButton.setValue(radioButton.getText().equals(addItemKindSelectedLabel));
}

Related

How to add items dynamically to a list box in GWT

I need to add items dynamically on click of listbox in Gwt . Which handler do I need to use?
Later I will be able to use addChangeHandler once items are added to listbox.
If i use click handler to add items to listbox, items are added to listbox. But on click of listbox, listbox items are not listed. Listbox closes immediately on click of it.
How to resolve this issue
Here is a simple code to demonstrate how to add items to the ListBox.
You need to understand some things first:
ClickEvent is fired whenever you click on the ListBox: first when you click to show the list and second when you click to select an item;
ChangeEvent is fired when you change the selected item - you can not use it to track the change of item list itself;
public class ListBoxTest implements EntryPoint {
private TextArea log = new TextArea();
private ListBox listBox = new ListBox();
private int i;
#Override
public void onModuleLoad() {
for(int j = 0; j < 5; j++)
listBox.addItem("item " + i++);
listBox.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
log(event.toDebugString());
for(int j = 0; j < 5; j++)
listBox.addItem("item " + i++);
}
});
listBox.addChangeHandler(new ChangeHandler() {
#Override
public void onChange(ChangeEvent event) {
log(event.toDebugString());
}
});
RootPanel.get().add(listBox);
RootPanel.get().add(log);
}
private void log(String text) {
String logText = log.getText();
if(!logText.isEmpty())
logText+= "\n";
logText+= text;
log.setText(logText);
}
}

Swap the type of link depending on model object

I'm at complete loss how to proceed further:
I have panel with a DropDownChoice and a submit button next to it. Depending on the selected value of the DropDownChoice (Obtained upon the firing of a OnChangeAjaxBehavior attached to it, the submit button needs to either replace the whole panel with a different one, OR become an ExternalLink.
Currently, the code looks like that:
public class ReportSelectionPanel extends Panel {
protected OptionItem selectedOption ;
public ReportSelectionPanel(String id) {
super(id);
IModel<List<OptionItem>> choices = new AbstractReadOnlyModel() {
// Create a list of options to be displayed in the DropDownChoice
} ;
final IModel<OptionItem> optionModel =
new PropertyModel<OptionItem>(this,"selectedOption") ;
final DropDownChoice<OptionItem> options =
new DropDownChoice("selectChoice",optionModel,choices) ;
// I don't know what the button should be... Plain Button? A Link?
final Component button = ???
options.add( new OnChangeAjaxBehavior() {
protected void onUpdate(AjaxRequestTarget target) {
if ( selectedOption.getChild() == null ) {
// button becomes an ExternalLink.
// A new window will popup once button is clicked
} else {
// button becomes a Something, and upon clicking,
// this ReportSelectionPanel instance gets replaced by
// an new Panel instance, the type of which is
// selectedOption.getChild()
}
} ) ;
I'm really not quite sure what the commented lines should become to achieve the result. Any suggestions?
Thanks!
Eric
IMHO it's nicer to keep just one button and just react differently depending on the selected option:
final Component button = new AjaxButton("button") {
public void onClick(AjaxRequestTarget target) {
if (selectedOption.getChild() == null) {
PopupSettings popup = new PopupSettings();
popup.setTarget("'" + externalUrl + "'");
target.appendJavascript(popup.getPopupJavaScript());
} else {
ReportSelectionPanel.this.replaceWith(new ReportResultPanel("..."));
}
}
};
// not needed if options and button are inside a form
// options.add( new OnChangeAjaxBehavior() { } ) ;

GWT - Finding which button is checked in a Dynamically generated list of Radiobuttons

I have a for loop that displays a list of text fields and radio buttons.
What is the best way to reference the widgets so that I can read the text fields and aslo find which radio button is checked.
Here is my loop
for(int x = 0; x<getLoopCount(); x++)
{
answerTable.setWidget(x,0, new Label("Answer:"));
answerTable.setWidget(x,1, new TextBox());
answerTable.setWidget(x,2, new RadioButton(""));
}
Is there a way to ID each widget so I can reference it?
I would recommend grouping the three widgets together in a composite widget like this:
class AnswerComposite extends Composite {
private final Label label;
private final TextBox textBox;
private final RadioButton radioButton;
public AnswerComposite() {
label = new Label("Answer:");
textBox = new TextBox();
radioButton = new RadioButton("answerGroup");
HorizontalPanel contentPanel = new HorizontalPanel();
contentPanel.add(label);
contentPanel.add(textBox);
contentPanel.add(radioButton);
initWidget(contentPanel);
}
public String getText() {
return textBox.getValue();
}
public boolean isSelected() {
return radioButton.getValue();
}
}
You can then add them to a panel and/or put them in a list like this:
VerticalPanel answersPanel = new VerticalPanel();
List<AnswerComposite> answerComposites = new ArrayList<AnswerComposite>();
for (int i = 0; i < getLoopCount(); i++) {
AnswerComposite answerComposite = new AnswerComposite();
answersPanel.add(answerComposite);
answerComposites.add(answersComposite);
}
Checking your widgets then becomes very easy:
answerComposites.get(i).getText();
answerComposites.get(i).isSelected();
It will probably also be convenient to add a ValueChangeHandler to your RadioButtons (see enrybo's answer).
You can add a ValueChangeHandler to your RadioButton when you are creating them.
for(int x = 0; x<getLoopCount(); x++){
answerTable.setWidget(x,0, new Label("Answer:"));
answerTable.setWidget(x,1, new TextBox());
RadioButton rb = new RadioButton("");
rb.addValueChangeHandler(new ValueChangeHandler(){
#Override
void onValueChange(ValueChangeEvent<Boolean> event){
// Do something
}
});
answerTable.setWidget(x,2, rb);
}
The ValueChangeEvent will only be fired when the RadioButton is checked. It will not fire if another RadioButton in the same group is checked.
Since you're adding the ValueChangeHandler as you're creating your RadioButton you should know what is to be done with it without having to create an ID for it.
Let me give you an adhoc answer, so don't care about the syntax but the algorithmic idea.
Extend GWT button.
abstract class MyButton
extends Button{
// provide the appropriate constructor in impl class,
// especially if using uibinder
abstract public void helloDolly(... args ...);
}
Instantiate all those buttons using MyButton.
MyButton[] buttons = {
new MyButton(){
public void helloDolly(... args ...){
Window.alert("allo allo #1");
}
},
new MyButton(){
public void helloDolly(... args ...){
Window.alert("allo allo #2");
}
},
// blah blah black sheep ....
}
Use clickEvent.getSource() when defining handler.
buttons[i].addEventHandler(
new ClickHandler(ClickEvent click){
Object src = click.getSource();
if (src !instanceOf MyButton){
throw new MyAngryException("For goodness' sake, pls use MyButton");
// or ignore
return;
}
((MyButton)src).helloDolly(... args ...);
}
)

GWT - implement ClickHandler event on a row of a FlexTable

So my software is displaying a flextable (the data is grabbed and displayed from a database) with users allowing to click on a checkbox to select a data.
//users is the flextable object.
userCheck = new ClickHandler() {
public void onClick(ClickEvent event) {
CheckBox src = (CheckBox) event.getSource();
for (int i = 1, n = users.getRowCount(); i < n; i++) {
CheckBox box = (CheckBox) users.getWidget(i, 0);
if (!box.equals(src)) {
box.setValue(false, false);
}
}
removeUserButton.setEnabled(src.getValue());
editUserButton.setEnabled(src.getValue());
}
};
The code above works, but now I'm trying to implement an action where instead of the user clicking on the checkbox, I want the user to click on a row (which ever cell of the table) and make the whole row (where the user have selected) to be highlighted. So I implemented this code below but so far it doesn't work (like the mouseclick won't register, I've yet to implement the color stuff yet.. :( ). Any suggestions?
userRowCheck = new ClickHandler() {
public void onClick(ClickEvent event) {
Cell src = users.getCellForEvent(event);
int rowIndex = src.getRowIndex();
System.out.println("Cell Selected: userRowCheck Handler, rowIndex: " + rowIndex);
//This is just to check if this method is even called out. And well, it doesn't.
}
};
Thanks very much!!!!
If you added userRowCheck to the FlexTable : myFlexTable.addClickHandler(userRowCheck); it should work. Just make sure you test src for null, because if you didn't put a widget in a cell and the user clicks on that cell it returns null.

GWT - GXT - How to get Radio Button Value?

I am using GWT (Google Web Toolkit) 1.5.3 et GXT (ExtJS) 1.2
I just want to create a simple form with some radio buttons generated after a RPC call, to get some values
Code:
final FormPanel simple = new FormPanel();
simple.setFrame(true);
simple.setWidth(350);
simple.setHeaderVisible(false);
DateField date = new DateField();
date.setFieldLabel("Date");
simple.add(date);
ListFluxServiceAsync service = (ListFluxServiceAsync)
GWT.create(ListFluxService.class);
ServiceDefTarget target = (ServiceDefTarget)service;
String url = GWT.getModuleBaseURL() + "flux.rpc";
target.setServiceEntryPoint(url);
final RadioGroup radioGroup = new RadioGroup("RadioGroup");
radioGroup.setFieldLabel("Flux");
radioGroup.setOrientation(Orientation.VERTICAL);
service.getAllFlux(new AsyncCallback<List<FluxModelData>>(){
public void onFailure(Throwable caught) {
GWT.log("flux.rpx::onFailure", caught);
MessageBox.alert("what?", "onFailure :" + caught.getMessage(), null);
}
public void onSuccess(List<FluxModelData> result) {
Iterator<FluxModelData> it = result.iterator();
while ( it.hasNext() ){
FluxModelData fmd = it.next();
Radio radio = new Radio();
radio.setName("flux");
radio.setValue(true);
//radio.setRawValue("my very long value");
radio.setBoxLabel(fmd.getDescription());
radioGroup.add(radio);
}
simple.add(radioGroup);
simple.layout(); //we need it to show the radio button
}
});
simple.setButtonAlign(HorizontalAlignment.CENTER);
Button button = new Button("Récupérer");
button.addSelectionListener(new SelectionListener<ButtonEvent>(){
#Override
public void componentSelected(ButtonEvent ce) {
MessageBox.alert("what?", radioGroup.getValue().getRawValue() , null);
}});
simple.addButton(button);
RootPanel.get().add(simple);
My problem is I can't set/get radio button value.
If I try the setRawValue("xxxxxxx"), I will get some null errors, while setting setValue(boolean) is working but I was expecting getting the radio value and not the label value.
Any Idea?
Create radio
Radio radio = new Radio();
radio.setBoxLabel("Si");
radio.setValue(true);
radio.setValueAttribute("true");
Radio radio2 = new Radio();
radio2.setBoxLabel("No");
radio2.setValueAttribute("false");
RadioGroup radioGroup = new RadioGroup();
radioGroup.setFieldLabel("Afecto");
radioGroup.add(radio);
radioGroup.add(radio2);
get selected value
Boolean b = Boolean.parseBoolean(radioGroup.getValue().getValueAttribute());
You need to extend the GWT RadioButton class ex:
public class ExtRadioButton extends RadioButton {
public ExtRadioButton(String name, String label) {
super(name, label);
// TODO Auto-generated constructor stub
}
public void setValue(String value)
{
Element span = getElement();
Element input = DOM.getChild(span,0);
DOM.setElementAttribute(input,"value",value);
}
}
Default it allows only boolean value. After initializing the radio button you need set the value.
Using radioButton.setItemId() and getItemId() resolve it.
Check out this
Radio radio1 = new Radio();
.............
Radio radio2 = new Radio();
.............
in order to get value you can do as follow
String value = (radio1.getValue()) ? radio1.getText() : radio2.getText();
Radio includeButton = new Radio();
Radio excludeButton = new Radio();
RadioGroup radioGroup = new RadioGroup();
radioGroup.add(includeButton);
radioGroup.add(excludeButton);
includeButton.setvalue(true)//false
I use radio.setAttributeValue() method to set value for the radio button.
The other way to do this is to use the radio.setValueAttribute(String) method. Then you can use the following code on the RadioGroup to get the set 'value' attribute of the clicked Radio button:
radioGroup.addListener(Events.Change, new Listener<BaseEvent>() {
#Override
public void handleEvent(BaseEvent be)
{
final RadioGroup radioGroup = (RadioGroup)be.getSource();
final Radio clickedRadioBtn = radioGroup.getValue();
final String valueAttribute = clickedRadioBtn.getValueAttribute(); // Correct !!!
}
});