can a listfield in blackberry be divided into 2 halves? - blackberry

i am developing a simple calculator application in blackberry now, and i am new to that environment.
i want to develop an application(calculator) which runs in a list like. probably there will be more simpler ways for implementing this. but i want to study with my stuff.
value1 : (numeric textfield)
value1 : (numeric textfield)
+ : (result(value1+value2))
- : (result(value1-value2))
* : (result(value1*value2))
/ : (result(value1/value2))
for this application, I have developed using eclipse as..
public class Scr_Main extends MainScreen
{
String my_array[] = new String[]{"+", "-", "*","/"};
EditField editfield_value1,editfield_value2;
ObjectListField my_list;
GridFieldManager gfm;
public Scr_Main()
{
this.setTitle("Address Book");
//Defining Components
gfm = new GridFieldManager(1, 1, 0);
editfield_value1 = new EditField("Enter Value :", "");
add(gfm);
gfm = new GridFieldManager(1, 1, 0);
editfield_value2 = new EditField("Enter Value :", "");
add(gfm);
my_list= new ObjectListField();
my_list.set(my_array);
add(my_list);
}
}
Now my question is how can i divide the list into two halves. or do i need to add one more list? or is there any way a list to be divided into two halves?

Override the ListFieldCallback.drawListRow() method to customise the way each row is painted.

Related

Update autoComplete JavaFx?

I'm currently working on a JavaFX project.I'm using Autcomplete TextField of ControlFx .Each time i add new rows in database table, it should to update Autocomplete ,i did this but my problem is showing double Context-Menu ,we can say double autocompletes because i call method that create autocomplete each adding of new elements in table.
When i click a tab editBill i call this method :
public void showEditBill() {
if (!BillPane.getTabs().contains(EditBillTab)) {
BillPane.getTabs().add(EditBillTab);
}
SingleSelectionModel<Tab> selectionModel = BillPane.getSelectionModel();
selectionModel.select(EditBillTab);
/*it should remove the old autocomplete from textfield*/
pushBills(); //Call for cheking new items
}
pushBills method () :
public void pushBills() {
ArrayList list = new ArrayList<>();
bills = new BillHeaderDao().FindAll();
for (int i = 0; i < bills.size(); i++) {
list.add(bills.get(i).getIdClient());
}
//How can i remove the old bind before bind again
autoCompletionBinding = TextFields.bindAutoCompletion(SearchBill, SuggestionProvider.create(list));
}
How i can remove the old autocomplete and bind new automplete?
Just in any case if you need to keep instance of AutoCompletionTextFieldBinding object, thus avoiding use of:
autoCompleteBinding = TextFields.bindingAutoCompletion(TextField,List);
, which will change the instance, we could go a little bit deeper and use this:
// let's suppose initially we have this possible values:
Set<String> autoCompletions = new HashSet<>(Arrays.asList("A", "B", "C"));
SuggestionProvider<String> provider = SuggestionProvider.create(autoCompletions);
new AutoCompletionTextFieldBinding<>(textField, provider);
// and after some times, possible autoCompletions values has changed and now we have:
Set<String> filteredAutoCompletions = new HashSet<>(Arrays.asList("A", "B"));
provider.clearSuggestions();
provider.addPossibleSuggestions(filteredAutoCompletions);
So, through SuggestionProvider, we have "updated" auto completion values.
To avoid doubling of suggestions menu, don't use again (for the 2nd time):
TextFields.bindAutoCompletion(..)
In order to provide updates to the auto-complete suggestion list, retain a reference to the SuggestionProvider and update the suggestion provider instead:
TextField textField = new TextField();
SuggestionProvider suggestionProvider = SuggestionProvider.create(new ArrayList());
new AutoCompletionTextFieldBinding<>(textField, suggestionProvider);
When you want to update the suggestion list:
List<String> newSuggestions = new ArrayList();
//(add entries to list)
suggestionProvider.clearSuggestions();
suggestionProvider.addPossibleSuggestions(newSuggestions);
This will do the trick:
Instead of: TextFields.bindAutoCompletion(textField, list);
, try this:
List<String> strings = new ArrayList<>();
Then create binding between your textField with the list through:
new AutoCompletionTextFieldBinding<>(textField, SuggestionProvider.create(strings));
So any changes, including removing, from the list, will be reflected in the autoCompletion of the textField;
And you will have dynamic filtering of suggestions, showed in pop-up, when user enter some text in textField;
I had the same problem some time ago I try to do as #MaxKing mentions, but it didnt work. I managed to give it a soluciĆ³n even though I don't think it's the right way.
// Dispose the old binding and recreate a new binding
autoCompleteBinding.dispose();
autoCompleteBinding = TextFields.bindingAutoCompletion(TextField,List);
try this:
public void pushBills() {
ArrayList list = new ArrayList<>();
bills = new BillHeaderDao().FindAll();
for (int i = 0; i < bills.size(); i++) {
list.add(bills.get(i).getIdClient());
}
autoCompletionBinding.dispose();
autoCompletionBinding = TextFields.bindAutoCompletion(SearchBill, SuggestionProvider.create(list));
}

Replacement for collapseItemsRecursively and expandItemsRecursively in Vaadin 8.1 TreeGrid

Vaadin 8.1 introduced the TreeGrid component. It does not have the collapseItemsRecursively and expandItemsRecursively methods anymore (as available in the now legacy Tree component). Do i miss something or do you need to develop your own implementation? If so, what is a recommended way of doing this?
As I'm sure you've noticed, the TreeGrid is a rather new component, currently being developed and available starting with v8.1.alphaX (current stable version is v8.0.6). As such, it probably has only some basic functionalities for the time being, with the rest to follow sometime in the future, although there are no guarantee. For example this similar feature request for the older TreeTable component has been in open state since 2011.
Either way, even if they're probably not the optimum solutions, there are a couple of work-arounds that you can use to achieve this behavior. I'm shamelessly using as a base sample, a slightly modified version of the code currently available in the vaadin-sampler for TreeGrid.
public class RecursiveExpansionTreeGrid extends VerticalLayout {
private Random random = new Random();
public RecursiveExpansionTreeGrid() {
// common setup with some dummy data
TreeGrid<Project> treeGrid = new TreeGrid<>();
treeGrid.setItems(generateProjectsForYears(2010, 2016), Project::getSubProjects);
treeGrid.addColumn(Project::getName).setCaption("Project Name").setId("name-column");
treeGrid.addColumn(Project::getHoursDone).setCaption("Hours Done");
treeGrid.addColumn(Project::getLastModified).setCaption("Last Modified");
addComponent(treeGrid);
}
// generate some dummy data to display in the tree grid
private List<Project> generateProjectsForYears(int startYear, int endYear) {
List<Project> projects = new ArrayList<>();
for (int year = startYear; year <= endYear; year++) {
Project yearProject = new Project("Year " + year);
for (int i = 1; i < 2 + random.nextInt(5); i++) {
Project customerProject = new Project("Customer Project " + i);
customerProject.setSubProjects(Arrays.asList(
new LeafProject("Implementation", random.nextInt(100), year),
new LeafProject("Planning", random.nextInt(10), year),
new LeafProject("Prototyping", random.nextInt(20), year)));
yearProject.addSubProject(customerProject);
}
projects.add(yearProject);
}
return projects;
}
// POJO for easy binding
public class Project {
private List<Project> subProjects = new ArrayList<>();
private String name;
public Project(String name) {
this.name = name;
}
public String getName() {
return name;
}
public List<Project> getSubProjects() {
return subProjects;
}
public void setSubProjects(List<Project> subProjects) {
this.subProjects = subProjects;
}
public void addSubProject(Project subProject) {
subProjects.add(subProject);
}
public int getHoursDone() {
return getSubProjects().stream().map(project -> project.getHoursDone()).reduce(0, Integer::sum);
}
public Date getLastModified() {
return getSubProjects().stream().map(project -> project.getLastModified()).max(Date::compareTo).orElse(null);
}
}
// Second POJO for easy binding
public class LeafProject extends Project {
private int hoursDone;
private Date lastModified;
public LeafProject(String name, int hoursDone, int year) {
super(name);
this.hoursDone = hoursDone;
lastModified = new Date(year - 1900, random.nextInt(12), random.nextInt(10));
}
#Override
public int getHoursDone() {
return hoursDone;
}
#Override
public Date getLastModified() {
return lastModified;
}
}
}
Next, recursively expanding or collapsing the nodes depends a bit on your scenario, but basically it breaks down to the same thing: making sure each node from the root to the deepest leaf is expanded/collapsed.The simplest way of doing it is to flatten your hierarchy into a list of nodes, and call the appropriate method, expand(List<T> items) or expand(T ... items) (the second delegates to the first and is probably a convenience method eg expand(myItem)).
For simplicity, I've added a flatten method in our Project implementation. If you can't do that for some reason, then create a recursive method that creates a list starting with the selected node and includes all the children, of the children, of the children.... well, you get the idea.
public Stream<Project> flatten() {
return Stream.concat(Stream.of(this), getSubProjects().stream().flatMap(Project::flatten));
}
Possible scenarios:
Automatically expand the entire hierarchy when expanding the root - add listeners, and expand/collapse the whole flattened hierarchy:
treeGrid.addCollapseListener(event -> {
if (event.isUserOriginated()) {
// event is triggered by all collapse calls, so only do it the first time, when the user clicks in the UI
// and ignore the programmatic calls
treeGrid.collapse(event.getCollapsedItem().flatten().collect(Collectors.toList()));
}
});
treeGrid.addExpandListener(event -> {
if (event.isUserOriginated()) {
// event is triggered by all expand calls, so only do it the first time, when the user clicks in the UI
// and ignore the programmatic calls
treeGrid.expand(event.getExpandedItem().flatten().collect(Collectors.toList()));
}
});
Expanding the hierarchy or part of it with a custom action, such as a context menu
GridContextMenu<Project> contextMenu = new GridContextMenu<>(treeGrid);
contextMenu.addGridBodyContextMenuListener(contextEvent -> {
contextMenu.removeItems();
if (contextEvent.getItem() != null) {
Project project = (Project) contextEvent.getItem();
// update selection
treeGrid.select(project);
// show option for expanding
contextMenu.addItem("Expand all", VaadinIcons.PLUS, event -> treeGrid.expand((project).flatten().collect(Collectors.toList())));
// show option for collapsing
contextMenu.addItem("Collapse all", VaadinIcons.MINUS, event -> treeGrid.collapse((project).flatten().collect(Collectors.toList())));
}
});
In the end, you should be getting this effect:
From the docs for treegrid, you can use the methods, collapse and expand, by passing a list or array of the treegrid's data items to expand or collapse:
treeGrid.expand(someTreeGridItem1, someTreeGridItem2);
treeGrid.collapse(someTreeGridItem1);
Also worthy of note, is a section showing the ability to prevent certain items from ever being collapsed

Vaadin Grid Row Index

In a vaadin table if we do
table.setRowHeaderMode(RowHeaderMode.INDEX);
we get a column with the row index.
Is it possible to to the same with a vaadin grid?
So far I haven't seen such an option, but you should be able to fake it with a generated column. Please see below a naive implementation which should get you started (improvements and suggestions are more than welcome):
// our grid with a bean item container
Grid grid = new Grid();
BeanItemContainer<Person> container = new BeanItemContainer<>(Person.class);
// wrap the bean item container so we can generated a fake header column
GeneratedPropertyContainer wrappingContainer = new GeneratedPropertyContainer(container);
wrappingContainer.addGeneratedProperty("rowHeader", new PropertyValueGenerator<Long>() {
private long index = 0;
#Override
public Long getValue(Item item, Object itemId, Object propertyId) {
return index++;
}
#Override
public Class<Long> getType() {
return Long.class;
}
});
// assign the data source to the grid and set desired column order
grid.setContainerDataSource(wrappingContainer);
grid.setColumnOrder("rowHeader", "name", "surname");
// tweak it a bit - definitely needs more tweaking
grid.getColumn("rowHeader").setHeaderCaption("").setHidable(false).setEditable(false).setResizable(false).setWidth(30);
// freeze the fake header column to prevent it from scrolling horizontally
grid.setFrozenColumnCount(1);
// add dummy data
layout.addComponent(grid);
for (int i = 0; i < 20 ; i++) {
container.addBean(new Person("person " + i, "surname " + i));
}
This will generate something similar to the image below:
There is a Grid Renderer that can be used to do this now. It is in the grid renderers add-on https://vaadin.com/directory/component/grid-renderers-collection-for-vaadin7. It is compatible with Vaadin 8 as well.
Here is how it could be used (there are a few different options for how to render the index).
grid.addColumn(value -> "", new RowIndexRenderer()).setCaption("Row index");
Worth to mention that I use the following with Vaadin 18 flow and works perfectly.
grid.addColumn(TemplateRenderer.of("[[index]]")).setHeader("#");
Ok, it took me more than a while to figure this out. I don't know why you need this, but if your purpose is to find which grid row was clicked, then you can get the index from the datasource of your control via the itemClick event of your listener.
In my case, my datasource is an SQLContainer, and I already had it available (see ds var) so I did it this way:
grid.addListener(new ItemClickEvent.ItemClickListener() {
#Override
public void itemClick(ItemClickEvent event) {
Object itemId = event.getItemId();
int indexOfRow = ds.indexOfId(itemId);
}
});
You usually add a datasource to your control when you initialize it, via constructor or by setting the property. If you got you Grid from somewhere with an already-attached datasource, you can always get it with something like this:
SQLContainer ds = (SQLContainer)gred.getContainerDataSource();
I use this trick:
int i = 0;
grid.addComponentColumn(object -> {
i++;
return new Label("" + i);
}).setCaption("");

How to add new Columns to table in Vaadin and how to place a link in vaadin table

I am new To Vaadin, I have created a Table and i can able to populate the data in that through the BeanItemCOntainer, bellow is the code for this.
public Component getMainContent(ViewChangeListener.ViewChangeEvent event) {
List<ExecutionPlanVO> executionPlanVOs = executionPlanDelegate.getExecutionPlans(getSearchVO());
Table table = new Table();
BeanItemContainer<ExecutionPlanVO> container = new BeanItemContainer<ExecutionPlanVO>(ExecutionPlanVO.class, executionPlanVOs);
container.addBean(new ExecutionPlanVO());
table.setContainerDataSource(container);
table.setVisibleColumns(
new Object[] {"billOfladingNo" , "containerNo" , "houseBill" , "carrier" , "customer" , "origin" , "pol" , "transshipment" ,
"pod" , "destination" , "start" , "completion" , "status"});
table.setColumnHeaders(
new String[] {"Bill Of Lading" , "Container No." , "House Bill" , "Carrier" , "Customer" , "Origin" , "POL" , "Transshipment" ,
"POD" , "Destination" , "Start (LT)" , "Completion (LT)" , "Status"});
table.setStyleName("ep-list-table");
return table;
}
I Have two questions here,
1. I would want to change billOfladingNo column as a link, which will permorm some action when i click ?
2. i wanted to add one more column with couple of link Icons?
can you help me how can i add the columns ?
Thanks in advance
Kiran.
You can Create a class to implement ColumnGenerator to return the link and the icon. I have done a sample below
class Linker implements ColumnGenerator{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Object generateCell(Table source, Object itemId, Object columnId) {
// TODO Auto-generated method stub
Item item = source.getItem(itemId);
Link link = new Link();
String linkCaption = item.getItemProperty("billOfladingNo").toString();
link.setCaption(linkCaption);
link.setResource(new ExternalResource("http:/www.domain.com/"+linkCaption));
return link;
}
}
class LinkIcons implements ColumnGenerator{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Object generateCell(Table source, Object itemId, Object columnId) {
// TODO Auto-generated method stub
Label icons = new Label();
icons.setIcon(FontAwesome.LINK);
return icons;
}
}
table.addGeneratedColumn("billOfLading", new Linker());
table.addGeneratedColumn("link", LinkIcons);
be sure to make your billoflading from the bean invisible and add the generated column ids to the table visible ids.
Depends what vaadin version Your using if 7.X.X then:
You can set on the container what type is the chosen column:
container.addContainerProperty("billOfladingNo", new Link, null);
1st parameter is the property of Your column
2nd is the type You want to have
3rd is the default value
that will make Your column type: com.vaadin.ui.Link
to make a new Link with possible navigation:
Link link = new Link("CAPTION", new ExternalResource("URL"));
For the second question u need to set the link caption to accept HTML and then set the FontAwesome icon html:
link.setCaptionAsHtml(true);
link.setCaption(FontAwesome.ANCHOR.getHtml());

jqgrid + EF + MVC: Is it possible to export in excel, using always the same controller action?

I am using jqgrid (standard) with EF 4 + MVC3. I'd like to implement excel export and if possible using the same action controller used to populate the grid.
I wonder if is it possible / logical to pass an additional parameter, for example. Which method you would suggest me?
I ask this question because I am still approaching to implement excel export and I'd like to optimize / re-use code, if possible.
To generate excel, I'd like to use this library by Dr Stephen Walther, which has three types of output and allows to define headers too. Please tell me if you find it valid for my purpose.
About the jqgrid code, I found this interesting answer by Oleg, but I do not understand if could be applied to my needs.
Unfortunately, by now I only found parts of solutions for excel export with EF MVC, but no solution or complete examples...
Here's the _Index partial view containing my jqgrid
<table id="mygrid"></table>
<div id="pager2"></div>
jQuery("#mygrid").jqGrid({
url:'controller/jqIndex',
datatype: "json",
colNames:['id','field1', ...],
colModel:[
{name:'id',index:'id', width:55},
{name:'field1',index:'field1', width:90},
...
],
rowNum:10,
rowList:[10,20,30],
pager: '#pager2',
sortname: 'id',
viewrecords: true,
sortorder: "desc",
caption:"modal jquery + jqgrid test"});
jQuery("#list2").jqGrid('navGrid','#pager2',{edit:false,add:false,del:false});
//TODO
???
...some code to call the controller action with the `excel` parameter set `true`
CONTROLLER (BASED ON OLEG'S IMPLEMENTATION)
public ActionResult jqIndex(string sidx, string sord, int page, int rows, bool _search, string filters, bool excel) // note the excel parameter <<
{
var context = new TManagerContext();
var objectContext = context.ObjectContext();
var set = objectContext.CreateObjectSet<Ticket>();
var serializer = new JavaScriptSerializer();
Filters f = (!_search || string.IsNullOrEmpty(filters)) ? null : serializer.Deserialize<Filters>(filters);
ObjectQuery<Ticket> filteredQuery = (f == null ? (set) : f.FilterObjectSet(set));
filteredQuery.MergeOption = MergeOption.NoTracking; // we don't want to update the data
int totalRecords = filteredQuery.Count();
var pagedQuery = filteredQuery.Skip("it." + sidx + " " + sord, "#skip",
new ObjectParameter("skip", (page - 1) * rows))
.Top("#limit", new ObjectParameter("limit", rows));
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var queryDetails = (from e in pagedQuery
select new
{
e.TicketID,
e.field1,
...
}).ToList();
var result = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from e in queryDetails
select new
{
id = e.TicketID,
cell = new string[]
{
e.field1,
...
}
}).ToArray()
};
if (excel) {
ExportExcel(result); // if possible, pass filter parameters too, column order, etc...
}
return Json(result, JsonRequestBehavior.AllowGet);
}
Please sorry if the question could be silly, I am just a (enthusiast) beginner.
Thanks for your precious help!
Best Regards
Larry - A few comments.
You shouldn't be doing that much logic in your controller. Move all
of that business logic to another class/service. Then your action
method would be just a few lines. A quick example
public JsonResult jqIndex(string sidx, string sord, int page, int rows,
bool _search, string filters){
return JSON(this.GridQueryService.GetJQGrid(sidx,sord,page,rows,_search,filters), JsosnRequestBehavior.AllowGet);
}
2.I know you don't want to repeat code (which point 1 helps) but there are many parameters and things here that simply do not apply to Excel (page, rows).
3.Passing boolean parameters to change how things function can get messy fast. Lets assume that you now need to pass more/less data to the Excel file, now you have nested conditions all over the place and Unit Testing would just be crappy.
4.An excel action method will should have a FileResult return type, not a
JSON result (I guess they are all action results, but this makes your intention all the more clear in your code. Your definition should be something like
public FileResult GetExcelFile(string sidx, string sord, bool _search,
string filters){
//do stuff to return Excel
}
If you create your Service in point one in such a way that you have two methods that return different items, but share a common query/search base function, then you are really staying Dry while following the Single Responsibility Principle. An example of this service might be (very rough example, should give you some things to think about):
public class GridQueryService{
public YourViewModel GetJQGrid(sidx, page, row, _search, filters){
//Get the base data
var myData = this.GetGridData(sidx, _search, filters);
//Create your view model and return it back to controller
}
public StreamWriter GetExcelFIle(sidx, _search, filters){
//Get the base data
var myData = this.GetGridData(sidx, _search, filters);
//Create your Excel file and return it to the controller
}
private ObjectQuery<Ticket> GetGridData(string sidx, bool _search, string filters){
//do your data grabbing here - you never return the raw data back to anything outside
//of this service, so it should be ok to make private
}
}

Resources