How to get the selected item as String in a Blackberry AutoCompleteField? - blackberry

How to get the selected Item as string when using a Blackberry AutoComplete Field. I am able to get the selected index currently. I am Overriding the onSelect method in the AutoCompleteField class as explained at
Autocomplete Class Reference API JDE 5.0
Code Snippet below -
AutoCompleteField autoCompleteField = new AutoCompleteField(filterList)
{
public void onSelect(Object selection, int SELECT_TRACKWHEEL_CLICK) {
ListField _list = getListField();
if (_list.getSelectedIndex() > -1) {
Dialog.alert("You selected: "+_list.getSelectedIndex());
// get text selected by user and do something...
}
}
};

The default implementation of AutoCompleteField#onSelect(Object, int) sets the text of the AutoCompleteField object's AutoCompleteFieldEditField to the select parameter. So you could query for the String that way. Here's a snippet of what I mean:
AutoCompleteField autoCompleteField = new AutoCompleteField(filterList)
{
public void onSelect(Object selection, int type) {
super.onSelect(selection, type);
if(selection != null) {
String selectionAsString = getEditField().getText();
// Do whatever else you need to do with the String.
}
}
};

/*
onSelect
protected void onSelect(Object selection,
int type)
Parameters:
*selection - The selected item*
type - The method of selection. This will be one of SELECT_TRACKWHEEL_CLICK SELECT_TRACKBALL_CLICK SELECT_ENTER
*/
BasicFilteredList filterList = new BasicFilteredList();
String[] days = {"Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday","Sunday"};
filterList.addDataSet(1,days,"days",BasicFilteredList.COMPARISON_IGNORE_CASE);
AutoCompleteField autoCompleteField = new AutoCompleteField(filterList){
protected void onSelect(Object selection, int type) {
BasicFilteredListResult result = (BasicFilteredListResult) selection;
Dialog.alert("You selected: "+ result._object);
super.onSelect(selection, type);
}
};
add(autoCompleteField);

Related

Is there a way to have the Combobox render the selected value like the Select in Vaadin Flow?

For example in the Select component the selected value is rendered as shown here. However when it comes to the ComboBox it is not rendered, only on the dropdown as shown here. I need to use the ComboBox because I need the search functionality, that is to have the item selected as they type in the value because there may be a lot of values. Ideally it would be great to merge the Select and ComboBox but barring that I'm wondering if there's a way to render the selected value.
You can't use an arbitrary Renderer, because the text input is, well, a text input. As noted in the comments below the question, what you're really after is an icon in front of the value of the input, and while there's no nice API in ComboBox for this, you can frankenstein together a solution using the prefix slot of the vaadin-text-field input. I've adapted an example using the Cookbook recipe here. Note that there's an enhancement request that would make handling prefix/suffix components in ComboBox easier: https://github.com/vaadin/flow-components/issues/1594
public class AboutView extends Div {
public AboutView() {
ComboBox<Person> comboBox = new ComboBox<>();
comboBox.setItems(getPersons());
// Renderer for the drop down
comboBox.setRenderer(new ComponentRenderer<Div, Person>(person -> {
Div container = new Div();
container.add(person.getIcon().create(), new Span(person.getName()));
return container;
}));
// on value change: either clear the prefix slot or create a new Icon there
comboBox.addValueChangeListener(e -> {
Person p = e.getValue();
if (p == null) {
PrefixUtil.clearSlot(comboBox, "prefix");
return;
}
PrefixUtil.setPrefixComponent(comboBox, p.getIcon().create());
});
comboBox.setItemLabelGenerator(Person::getName);
add(comboBox);
}
public List<Person> getPersons() {
List<Person> persons = new ArrayList<>();
Person person1 = new Person("Foo", VaadinIcon.ARROW_BACKWARD);
Person person2 = new Person("Bar", VaadinIcon.BAR_CHART);
Person person3 = new Person("Baz", VaadinIcon.PUZZLE_PIECE);
persons.add(person1);
persons.add(person2);
persons.add(person3);
return persons;
}
public static class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
public VaadinIcon getIcon() {
return icon;
}
public void setIcon(VaadinIcon icon) {
this.icon = icon;
}
private VaadinIcon icon;
public Person(String name, VaadinIcon icon) {
this.name = name;
this.icon = icon;
}
}
public static class PrefixUtil {
private static Stream<Element> getElementsInSlot(HasElement target,
String slot) {
return target.getElement().getChildren()
.filter(child -> slot.equals(child.getAttribute("slot")));
}
public static void setPrefixComponent(Component target, Component component) {
clearSlot(target, "prefix");
if (component != null) {
component.getElement().setAttribute("slot", "prefix");
target.getElement().appendChild(component.getElement());
}
}
private static void clearSlot(Component target, String slot) {
getElementsInSlot(target, slot).collect(Collectors.toList())
.forEach(target.getElement()::removeChild);
}
private static Component getChildInSlot(HasElement target, String slot) {
Optional<Element> element = getElementsInSlot(target, slot).findFirst();
if (element.isPresent()) {
return element.get().getComponent().get();
}
return null;
}
public static Component getPrefixComponent(Component target) {
return getChildInSlot(target, "prefix");
}
}
}

Navigate into Listbox zk with radio component

I have this Listboxin ZUL page :
<listbox id="lstboxResult">
<listhead sizable="true">
<listheader label="Editore" />
<listheader id="lstAzienda" />
</listhead>
</listbox>
And a ListitemRender :
public void render(Listitem listitem, Object data, int index) throws Exception {
final String o = (String) data;
if (!o.equals("")) {
addListcell(listitem, String.valueOf(o));
addRadiogroup(listitem);
}
}
private void addListcell(Listitem listitem, String value) {
Listcell lc = new Listcell();
Label lb = new Label(value);
lb.setParent(lc);
lc.setParent(listitem);
}
private void addRadiogroup(Listitem listitem) {
Radio radAla = new Radio("Label1");
Radio radPeg = new Radio("Label2");
Radio radRw = new Radio("Label3");
Radiogroup rg = new Radiogroup();
radAla.setRadiogroup(rg);
radPeg.setRadiogroup(rg);
radRw.setRadiogroup(rg);
radAla.setParent(rg);
radPeg.setParent(rg);
radRw.setParent(rg);
Listcell lc = new Listcell();
rg.setParent(lc);
lc.setParent(listitem);
}
How can get data from listbox setting Label value in list cell and checked value?
The second column contains 3 radios and each represent a choice. I'd like to save these choices in the database. I need a POJO to save the label and the checkbox choice for each row.
You can achieve this by using a small object in your list model instead of String. When the radios are checked, you save the choice in that object. Then you can save it later.
Look at this example:
lstboxResult.setModel(new ListModelList<>(Arrays.asList(new MyObject("1"), new MyObject("2"))));
lstboxResult.setItemRenderer(new ListitemRenderer<MyObject>()
{
#Override
public void render(Listitem listitem, MyObject data, int index)
throws Exception
{
Listcell lc = new Listcell(value);
lc.setParent(listitem);
Radio radAla = new Radio("Label1");
Radio radPeg = new Radio("Label2");
Radio radRw = new Radio("Label3");
Radiogroup rg = new Radiogroup();
radAla.setRadiogroup(rg);
radPeg.setRadiogroup(rg);
radRw.setRadiogroup(rg);
radAla.setParent(rg);
radPeg.setParent(rg);
radRw.setParent(rg);
Listcell lc = new Listcell();
rg.setParent(lc);
lc.setParent(listitem);
rg.addEventListener(Events.ON_CHECK, e -> {
data.setSelectedIndex(rg.getSelectedIndex());
data.setSelectedLabel(rg.getSelectedItem() != null ? rg.getSelectedItem().getLabel() : null);
System.out.println(data.getLabel() + " " + data.getSelectedIndex() + " " + data.getSelectedLabel());
});
}
});
private static class MyObject
{
private String label;
private int selectedIndex = -1;
private String selectedLabel;
public MyObject(String label) { this.label = label; }
public String getLabel() { return label; }
public int getSelectedIndex() { return selectedIndex; }
public void setSelectedIndex(int selectedIndex) { this.selectedIndex = selectedIndex; }
public String getSelectedLabel() { return selectedLabel; }
public void setSelectedLabel(String selectedLabel) { this.selectedLabel = selectedLabel; }
}
Now you can use the model to read the chosen radios from the MyObjects and do whatever you want with them.

Right-align column contents in Vaadin Grid?

In the new Vaadin Grid widget (alternative to venerable Table), how does one right-align numbers or other content in a column?
The simplest way I can think of is to define your own CSS classes and style generator, pretty much similar to what I'd had done when working with tables.
#Theme("mytheme")
#Widgetset("com.matritza.MyAppWidgetset")
public class MyUI extends UI {
#WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
// meh, default stuff
}
#Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
// create a grid
Grid grid = new Grid("Grid test");
// create a specific container for the grid to hold our persons
BeanItemContainer<Person> container = new BeanItemContainer<>(Person.class);
grid.setContainerDataSource(container);
// define our own style generator
grid.setCellStyleGenerator(new Grid.CellStyleGenerator() {
#Override
public String getStyle(Grid.CellReference cellReference) {
if ("age".equals(cellReference.getPropertyId())) {
// when the current cell is number such as age, align text to right
return "rightAligned";
} else {
// otherwise, align text to left
return "leftAligned";
}
}
});
// generate some dummy data
for (int i = 0; i < 10; i++) {
container.addItem(new Person("Name " + i, "Surname " + i, i));
}
layout.addComponent(grid);
}
// basic class to populate the grid in a fast & simple way
public class Person {
private String name;
private String surname;
private int age;
private Person(String name, String surname, int age) {
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
And the basic CSS styles
#mixin mytheme {
#include valo;
// Insert your own theme rules here
.leftAligned {
text-align: left;
}
.rightAligned {
text-align: right;
}
}
And you should see something like
By the way, in Java 8 and later, the new Lambda syntax for that style generator would be:
grid.setCellStyleGenerator(( Grid.CellReference cellReference ) -> {
if ( "age".equals( cellReference.getPropertyId() ) ) {
// when the current cell is number such as age, align text to right
return "rightAligned";
} else {
// otherwise, align text to left
return "leftAligned";
}
});
One can also use already present styles like v-align-right, v-align-middle, etc. Just see what themes like Valo already contain, and extend existing themes only when needed.
Here's simple example how one could implement cell generator with regexp (matching one or multiple fields based on name of field)
public class RegexpCellStyleGenerator implements CellStyleGenerator {
private String regex = ".*"; // defaults all
String style = "v-align-right"; // default is here just as example
// special version useful only when one wants to style all fields inside grid
public RegexpCellStyleGenerator(String style) {
super();
this.style = style;
}
public RegexpCellStyleGenerator(String regex, String style) {
super();
this.regex = regex;
this.style = style;
}
#Override
public String getStyle(CellReference cellReference) {
String propertyId = cellReference.getPropertyId().toString();
if (propertyId.matches(regex)) {
return style;
}
return null;
}
and as this is only partially useful as most grids have multiple fields composite generator could be handy
public class CompositeCellStyleGenerator implements CellStyleGenerator {
List<CellStyleGenerator> generators = new ArrayList<>();
public CompositeCellStyleGenerator() {}
public void addCellStyleGenerator(CellStyleGenerator generator) {
generators.add(generator);
}
#Override
public String getStyle(CellReference cellReference) {
List<String> styles = new ArrayList<>();
for (CellStyleGenerator generator : generators) {
String style = generator.getStyle(cellReference);
if (style != null) {
styles.add(style);
}
}
if (!styles.isEmpty()) {
return styles.stream().collect(Collectors.joining(" "));
}
return null;
}
Composite generator joins all styles together and can be used like this. If there's multiple styles for one column both are applied.
RegexpCellStyleGenerator yearGenerator = new RegexpCellStyleGenerator("yearOfFoundation", "v-align-right");
RegexpCellStyleGenerator nameGenerator = new RegexpCellStyleGenerator("name", "v-align-center");
RegexpCellStyleGenerator nameGenerator2 = new RegexpCellStyleGenerator("name", "v-label-huge");
CompositeCellStyleGenerator compositeGenerator = new CompositeCellStyleGenerator();
compositeGenerator.addCellStyleGenerator(yearGenerator);
compositeGenerator.addCellStyleGenerator(nameGenerator);
compositeGenerator.addCellStyleGenerator(nameGenerator2);
grid.setCellStyleGenerator(compositeGenerator);
Note that composite generator can use generic generators like one with regexp definitions and more complex use case specific ones.
Hope this helps those who try to find easy way to style cells. Happy Experimenting.

How to select combobox by id or value using with BeanItemContainer?

I am using BeanItemContainer for my comboboxes to satisfy key-value pairs.
#SuppressWarnings("serial")
public class ComboBoxItem implements Serializable {
private String id;
private String description;
public ComboBoxItem(final String id, final String description) {
this.id = id;
this.description = description;
}
public final void setId(final String id) {
this.id = id;
}
public final void setDescription(final String description) {
this.description = description;
}
public final String getId() {
return id;
}
public final String getDescription() {
return description;
}
}
I created a sample combobox as below
List<ComboBoxItem> lstAuctionDateList = new ArrayList<ComboBoxItem>();
lstAuctionDateList.add(new ComboBoxItem("all", "All"));
BeanItemContainer<ComboBoxItem> auctionDateItems = new BeanItemContainer<ComboBoxItem>(ComboBoxItem.class,
lstAuctionDateList);
final ComboBox cbAuctionDate = new ComboBox("Auction Date", auctionDateItems);
cbAuctionDate.addStyleName("small");
cbAuctionDate.setNullSelectionAllowed(false);
cbAuctionDate.setTextInputAllowed(false);
cbAuctionDate.setItemCaptionPropertyId("description");
cbAuctionDate.addValueChangeListener(new ValueChangeListener() {
public void valueChange(final ValueChangeEvent event) {
if (cbAuctionDate.getValue() != null) {
System.out.println(((ComboBoxItem) cbAuctionDate.getValue()).getId());
System.out.println(((ComboBoxItem) cbAuctionDate.getValue()).getDescription());
}
}
});
It is fine but I can't select any of combobox items by using below codes
cbAuctionDate.select("all");
cbAuctionDate.select("All");
cbAuctionDate.setValue("all");
cbAuctionDate.setValue("All");
What am I wrong ? How can I select my comboxes by programmatically ?
when using a (bean) container and adding items, the identity of the item itself is used as the itemId in the container. E.g. cbActionDate.select(lstAuctionDateList[0]) should work.
You either have yo make your objects immutable or use ways to tell the container, what it has to use for an id (E.g. setBeanIdProperty("id") or setBeanIdResolver).
Making the object immutable should be easy right now (make the class and the private attributes final, drop the setters and let your IDE generate equals and hashCode for you)
You don't need the cbAuctionDate.addItem("All") call, you already have such a item in your collection
I would try it that way:
List<ComboBoxItem> lstAuctionDateList = new ArrayList<ComboBoxItem>();
ComboBoxItem allItems= new ComboBoxItem("all", "All");
lstAuctionDateList.add(allItems);
....
...
cbAuctionDate.select(allItems);
Now I created custom ComboBox component for my problem
public class ComboBox extends CustomComponent implements Serializable {
private com.vaadin.ui.ComboBox comboBox;
private BeanItemContainer<ComboBoxItem> entries = new BeanItemContainer<ComboBoxItem>(ComboBoxItem.class);
public ComboBox() {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCompositionRoot(comboBox);
}
public ComboBox(final String caption) {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCaption(caption);
setCompositionRoot(comboBox);
}
public ComboBox(final String caption, final List<ComboBoxItem> items) {
comboBox = new com.vaadin.ui.ComboBox();
comboBox.addStyleName("small");
comboBox.setNullSelectionAllowed(false);
comboBox.setTextInputAllowed(false);
setCaption(caption);
if (items != null && items.size() > 0) {
entries.addAll(items);
comboBox.setContainerDataSource(entries);
comboBox.setItemCaptionMode(ItemCaptionMode.PROPERTY);
addItems(entries);
comboBox.select(items.get(0));
comboBox.setItemCaptionPropertyId("description");
}
setCompositionRoot(comboBox);
}
public final void addItems(final List<ComboBoxItem> items) {
if (items != null && items.size() > 0) {
entries.addAll(items);
comboBox.setContainerDataSource(entries);
comboBox.setItemCaptionMode(ItemCaptionMode.PROPERTY);
addItems(entries);
comboBox.select(items.get(0));
comboBox.setItemCaptionPropertyId("description");
}
}
private void addItems(final BeanItemContainer<ComboBoxItem> items) {
comboBox.addItems(items);
}
public final void addItem(final ComboBoxItem item) {
if (item != null) {
comboBox.setContainerDataSource(entries);
comboBox.addItem(item);
comboBox.setItemCaptionPropertyId("description");
}
}
public final void selectByIndex(final int index) {
Object[] ids = comboBox.getItemIds().toArray();
comboBox.select(((ComboBoxItem) ids[index]));
}
public final void selectById(final String id) {
Object[] ids = comboBox.getItemIds().toArray();
for (int i = 0; i < ids.length; i++) {
if (((ComboBoxItem) ids[i]).getId().equals(id)) {
selectByIndex(i);
break;
}
}
}
public final void selectByItemText(final String description) {
Object[] ids = comboBox.getItemIds().toArray();
for (int i = 0; i < ids.length; i++) {
if (((ComboBoxItem) ids[i]).getDescription().equals(description)) {
selectByIndex(i);
break;
}
}
}
public final int getItemCount() {
return comboBox.getItemIds().toArray().length;
}
public final String getSelectedId() {
return ((ComboBoxItem) comboBox.getValue()).getId();
}
public final String getSelectedItemText() {
return ((ComboBoxItem) comboBox.getValue()).getDescription();
}
public final void addValueChangeListener(final ValueChangeListener listener) {
comboBox.addValueChangeListener(listener);
}
}
and below is test codes
final ComboBox combo = new ComboBox("My ComboBox");
combo.addItem(new ComboBoxItem("all", "All"));
// Add with list
List<ComboBoxItem> items = new ArrayList<ComboBoxItem>();
items.add(new ComboBoxItem("one", "One"));
items.add(new ComboBoxItem("two", "Two"));
items.add(new ComboBoxItem("three", "Three"));
combo.addItems(items);
combo.addItem(new ComboBoxItem("four", "Four"));
combo.addItem(new ComboBoxItem("five", "five"));
combo.selectByIndex(3);
combo.addValueChangeListener(new ValueChangeListener() {
public void valueChange(final ValueChangeEvent event) {
System.out.println(combo.getSelectedId() + " --- " + combo.getSelectedItemText());
}
});

Refreshing Table Adapter screen : Blackberry

Is there any way to refresh Table Adapter Screen on button click.
If i m callling table method again on button click then it is adding a new table adapter screen below the old on.....I s there any way to refresh the existing screen.The button is deleting elements from table after which i want to refresh it.
public static void richlistshow(){
int ik = target_list.size()-1;
while(ik > 0 )
{
Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
City aCity = (City)target_list.elementAt(ik);
String modelNumber = aCity.get_city_name().toString();
String modelName = " X ";
//String ne = String.valueOf(ik);
String date_time = " Date-Time";
Object[] row = {modelName, modelNumber,date_time,logoBitmap};
_tableModel.addRow(row);
ik--;
}
TableView tableView = new TableView(_tableModel);
tableView.setDataTemplateFocus(BackgroundFactory.createLinearGradientBackground(Color.YELLOWGREEN, Color.LIMEGREEN, Color.SEAGREEN, Color.SANDYBROWN));
TableController tableController = new TableController(_tableModel, tableView);
tableController.setFocusPolicy(TableController.ROW_FOCUS);
tableView.setController(tableController);
// Specify a simple data template for displaying 3 columns
DataTemplate dataTemplate = new DataTemplate(tableView, NUM_ROWS, NUM_COLUMNS)
{
public Field[] getDataFields(int modelRowIndex)
{
//final int i =modelRowIndex;
Object[] data = (Object[]) (_tableModel.getRow(modelRowIndex));
final String cname = (String)data[1];
/****** Declaring button for deletion of record from database ******/
ButtonField delete =new ButtonField("X",ButtonField.CONSUME_CLICK);
/******* Setting change listener and defining field change within *******/
delete.setChangeListener(new FieldChangeListener() {
/******* defining what should happen when button is clicked ********/
public void fieldChanged(Field field, int context) {
DatabaseHandler delete_row = new DatabaseHandler();
delete_row.deletetarget(cname);
/****calling function to retrieve values from the databasse table.***/
delete_row.retrieveTarget();
/****************calling method again to show the updated values*************/
richlistshow();//for showing refreshed data after deletion of a record
}
});
Field[] fields = {delete, new LabelField((String) data[1]), new LabelField((String) data[2]),new BitmapField((Bitmap)data[3])};
return fields;
}
};
dataTemplate.useFixedHeight(true);
// Define regions and row height
dataTemplate.setRowProperties(0, new TemplateRowProperties(ROW_HEIGHT));
for(int i = 0; i < NUM_COLUMNS; i++)
{
dataTemplate.createRegion(new XYRect(i, 0, 1, 1));
dataTemplate.setColumnProperties(i, new TemplateColumnProperties(Display.getWidth() / NUM_COLUMNS));
}
// Apply the template to the view
tableView.setDataTemplate(dataTemplate);
mainManager.add(tableView);
}
public final static class MyCity
{
private String _name;
private String _datetime;
private String _button;
private Bitmap _bitmap;
MyCity(String name, String datetime, String button, Bitmap bitmap)
{
_name = name;
_datetime = datetime;
_button = button;
_bitmap = bitmap;
}
public String getName()
{
return _name;
}
public String getDatetime()
{
return _datetime;
}
public String getButton()
{
return _button;
}
public Bitmap getBitmap()
{
return _bitmap;
}
}
/****************TABLE CONTROLLER CLASS ******************/
private class CityTableModelAdapter extends TableModelAdapter
{
public int getNumberOfRows()
{
return _cities.size();
}
public int getNumberOfColumns()
{
return NUM_COLUMNS;
}
protected boolean doAddRow(Object row)
{
Object[] arrayRow = (Object[]) row;
System.out.println("! : "+arrayRow[0]+" #: "+arrayRow[1]+" #: "+arrayRow[2]);
_cities.addElement(new MyCity((String) arrayRow[0], (String) arrayRow[1], (String) arrayRow[2], (Bitmap) arrayRow[3]));
return true;
}
protected Object doGetRow(int index)
{
MyCity mycity = (MyCity) _cities.elementAt(index);
Object[] row = {mycity.getName(),mycity.getDatetime(),mycity.getButton(),mycity.getBitmap()};
return row;
}
}

Resources