Vaadin table | How to set colspan - vaadin

I'm using vaadin tree table, and I want to set 1st column colspan (equal to the total number of column in table) for some of the rows satisfying some business criteria. For the rest of table rows, individual columns will appear normally.
I've tried using generated columns, and by setting explicit column width, and also by having composite columns; but doing so changes the layout for all the row/columns. Kindly suggest how will we achieve this.
Thanks!

You can set the width of a column by calling TreeTable#setColumnExpandRatio(String columnName, float value).
In the example below, I've set the width of column "Name" to 75%. If you don't specify anything else, the rest of the columns will fit in the rest of the space.
ttable.setColumnExpandRatio("Name", 0.75f);
ttable.setColumnExpandRatio("Number", 0.25f); //not necessary
Try the example below that I modified from Vaadin book:
#Theme("mytheme")
public class MyUI extends UI {
#Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
layout.setSizeFull();
TreeTable ttable = new TreeTable();
ttable.addContainerProperty("Name", String.class, null);
ttable.addContainerProperty("Number", Integer.class, null);
//Add some sample data
ttable.addItem(new Object[]{"Menu", null}, 0);
ttable.addItem(new Object[]{"Beverages", null}, 1);
ttable.setParent(1, 0);
ttable.addItem(new Object[]{"Foods", null}, 2);
ttable.setParent(2, 0);
ttable.addItem(new Object[]{"Coffee", 23}, 3);
ttable.addItem(new Object[]{"Tea", 42}, 4);
ttable.setParent(3, 1);
ttable.setParent(4, 1);
ttable.addItem(new Object[]{"Bread", 13}, 5);
ttable.addItem(new Object[]{"Cake", 11}, 6);
ttable.setParent(5, 2);
ttable.setParent(6, 2);
ttable.setColumnExpandRatio("Name", 0.75f);
ttable.setColumnExpandRatio("Number", 0.25f);
ttable.setSizeFull();
layout.addComponents(ttable);
layout.setMargin(true);
layout.setSpacing(true);
setContent(layout);
}
#WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
}

You can use com.vaadin.ui.Table.setRowGenerator:
Example with Java 8 + Vaadin 7.6.1
setRowGenerator((Table table, Object itemId) -> {
if (itemId instanceof MyClassThatIdentifiesARowToMerge) {
Table.GeneratedRow generatedRow = new Table.GeneratedRow("text-of-merged-cell");
generatedRow.setSpanColumns(true);
return generatedRow; // merge
}
return null; // doesn't merge
} );

Related

Set results from math operations into Vaadin Grid in real time (Manually inserting), Using Vaadin 7

The main thing of my problem is, that I want inserting data into my grid from keyboard. Some data are loaded from the database, and user can change (can change the loaded data too) or insert the new data into grid (manually). Then I want have see the results from the columns in last rows (Check the results in my picture) - Results means the number in rows where in the first column is data like - sum, average, min, max ...
So, when I click on the third row, into column e.g Person 3, and when I will change the value from 5 to 6 and in this time the sum will be 16, max will be 6, min 1 and average will be 3.2
My code of Grid is:
Grid grid = new Grid();
IndexedContainer container = new IndexedContainer();
grid.setContainerDataSource(container);
container.addContainerProperty("September", String.class, null);
container.addContainerProperty("Person1", String.class, null);
container.addContainerProperty("Person2", String.class, null);
container.addContainerProperty("Person3", String.class, null);
container.addContainerProperty("Person4", String.class, null);
container.addContainerProperty("Person5", String.class, null);
container.addContainerProperty("Person6", String.class, null);
container.addContainerProperty("Person7", String.class, null);
container.addContainerProperty("Person8", String.class, null);
for(int i = 0; i < 10; i++)
container.addItem(i);
Item item = container.getItem(1);
item.getItemProperty("September").setValue("1.9.2017 Piatok");
item = container.getItem(2);
item.getItemProperty("September").setValue("2.9.2017 Sobota");
....
I tried to add the addValueChangeListener to the grid (container)
container.addValueChangeListener(e -> {
int sum = 0;
for(int i = 0; i < 5; i++)
{
Item item = container.getItem(i);
sum += (Integer) item.getItemProperty("Person3").getValue();
}
item = container.getItem(6);
item.getItemProperty("Person3").setValue(sum);
});
But I get the error message:
sep 15, 2017 4:16:21 PM com.vaadin.server.DefaultErrorHandler doDefault
SEVERE:
com.vaadin.data.Buffered$SourceException
at com.vaadin.ui.AbstractField.setValue(AbstractField.java:546)
at com.vaadin.ui.AbstractField.setValue(AbstractField.java:468)
at com.vaadin.ui.AbstractTextField.changeVariables(AbstractTextField.java:205)
at com.vaadin.server.communication.ServerRpcHandler.changeVariables(ServerRpcHandler.java:616)
at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(ServerRpcHandler.java:463)
at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:406)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:273)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:90)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1422)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:380)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:845)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1689)
at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:225)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1174)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1106)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle(Server.java:524)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.StackOverflowError
at java.util.Hashtable.get(Hashtable.java:366)
at com.vaadin.data.util.IndexedContainer$IndexedContainerProperty.setValue(IndexedContainer.java:848)
at my.vaadin.app.MyUI.lambda$11(MyUI.java:3931)
at com.vaadin.data.util.IndexedContainer.firePropertyValueChange(IndexedContainer.java:528)
at com.vaadin.data.util.IndexedContainer.access$1000(IndexedContainer.java:63)
at com.vaadin.data.util.IndexedContainer$IndexedContainerProperty.setValue(IndexedContainer.java:867)
at my.vaadin.app.MyUI.lambda$11(MyUI.java:3931)
Problem is when I try to change 2 and more cells ...
container.addValueChangeListener(e -> {
Item item = container.getItem(6);
if(!e.getProperty().equals(item.getItemProperty("Person3")))
item.getItemProperty("Person3").setValue(54 + "");
if(!e.getProperty().equals(item.getItemProperty("Person4")))
item.getItemProperty("Person4").setValue(65 + "");
});
How I can Fix it ?
This is the problem, I don't want have this footer always visible at the grid. I want see the footers only when I come to the end of the grid. Do you understand that?
This is already answered in Using Vaadin 7.4.9 - How to delete data from the grid
The cause is the same, you are calling container.setValue within the container.addValueChangeListener resulting in an endless loop.
You can NOT CALL item.getItemProperty("Person3").setValue(sum); within the listener.
You have to check if the item you are currently setting is not already set the last time you visited your loop.
Imagine the following:
int otherValue = 10;
public setValue(int newValue) {
int sum = newValue + otherValue; //this is your sum
setValue(sum); //of course this causes a StackOverFlowError
}
Here is a solution that could work for your project:
if(!e.getProperty().equals(item.getItemProperty("Person3"))
item.getItemProperty("Person3").setValue(sum);
Assuming by now you've figured out why you're getting a SOE by using a ValueChangeListener to update the sum row, you can overcome this problem with a similar approach by using an editor CommitHandler, so when the editor changes are saved, the sum row is updated. For the sake of brevity the sample below only calculates the sum, but you can apply similar logic for the rest of your operations:
public class GridWithCalculatedRow extends VerticalLayout {
public GridWithCalculatedRow() {
// indexed container allowing the definition of custom properties
IndexedContainer container = new IndexedContainer();
container.addContainerProperty("September", String.class, null);
container.addContainerProperty("Person1", Integer.class, 0);
container.addContainerProperty("Person2", Integer.class, 0);
container.addContainerProperty("Person3", Integer.class, 0);
// add some dummy data
Random random = new Random();
for (int i = 0; i < 5; i++) {
Item item = container.addItem(i);
item.getItemProperty("September").setValue(String.valueOf(i));
item.getItemProperty("Person1").setValue(random.nextInt(10));
item.getItemProperty("Person2").setValue(random.nextInt(10));
item.getItemProperty("Person3").setValue(random.nextInt(10));
}
Item sumItem = container.addItem(6);
sumItem.getItemProperty("September").setValue("Sum");
// basic grid setup
Grid grid = new Grid();
grid.setContainerDataSource(container);
grid.getColumn("September").setEditable(false);
addComponent(grid);
// initial sum
updateSum(container, sumItem);
// disable editing of sum item
grid.addItemClickListener(event -> {
if (event.getItemId().equals(6)) {
grid.setEditorEnabled(false);
} else {
grid.setEditorEnabled(true);
}
});
// editor commit handler to update the sum
grid.getEditorFieldGroup().addCommitHandler(new FieldGroup.CommitHandler() {
#Override
public void preCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {
// nothing to do here for now
}
#Override
public void postCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {
updateSum(container, sumItem);
}
});
}
// recalculate all sums and update the sum item
private void updateSum(IndexedContainer container, Item sumItem) {
Integer person1Sum = 0;
Integer person2Sum = 0;
Integer person3Sum = 0;
// calculate sums
for (int i = 0; i < 5; i++) {
Item item = container.getItem(i);
person1Sum += (Integer) item.getItemProperty("Person1").getValue();
person2Sum += (Integer) item.getItemProperty("Person2").getValue();
person3Sum += (Integer) item.getItemProperty("Person3").getValue();
}
// update grid item
sumItem.getItemProperty("Person1").setValue(person1Sum);
sumItem.getItemProperty("Person2").setValue(person2Sum);
sumItem.getItemProperty("Person3").setValue(person3Sum);
}
}
Result:

Vaadin, TreeTable. setParent

I have a problem with creating parent-child link in my TreeTable.
Setting of DataSource
table.setContainerDataSource(new TempPeopleContainer(((MyUI) UI.getCurrent()).peopleService.getItemList()));
table.setParent(1,0);
How can I set id of Object in this kind of DataSource setting? I've no explicit Id for elements of TreeTable.
Here is example from vaadin , where you can see "clearly" definition of Id's for each element (code not from my app):
TreeTable ttable = new TreeTable("My TreeTable");
ttable.addContainerProperty("Name", String.class, null);
ttable.addContainerProperty("Number", Integer.class, null);
ttable.setWidth("20em");
// Create the tree nodes and set the hierarchy
ttable.addItem(new Object[]{"Menu", null}, 0);
ttable.addItem(new Object[]{"Beverages", null}, 1);
ttable.setParent(1, 0);
ttable.addItem(new Object[]{"Foods", null}, 2);
ttable.setParent(2, 0);
it's my TempPeopleContainer class definition:
private class TempPeopleContainer extends FilterableListContainer<People> {
public TempPeopleContainer(final Collection<People> collection) {
super(collection);
}
// This is only temporarily overridden until issues with
// BeanComparator get resolved.
#Override
public void sort(final Object[] propertyId, final boolean[] ascending) {
final boolean sortAscending = ascending[0];
final Object sortContainerPropertyId = propertyId[0];
Collections.sort(getBackingList(), (o1, o2) -> {
int result = 0;
if ("lastname".equals(sortContainerPropertyId)) {
result = o1.getLastname().compareTo(o2.getLastname());
}
if (!sortAscending) {
result *= -1;
}
return result;
});
}
}
I hope my question is clear. Thanks.
It depends on your ItemContainer. The common BeanItemContainer from vaadin uses the item as item id itself as documented here https://vaadin.com/api/com/vaadin/data/util/BeanItemContainer.html
You are using vitrin's org.vaadin.viritin.ListContainer acting like the BeanItemContainer
So you could use the items from your list as itemId/newParentId if you want to stick at your ItemContainer implementations.
Or you could go the long way and get the item ids by iterating over com.vaadin.data.Container.getItemIds() and check manually if this item id is the parent id you want to use.
edit:
Try something like this:
List myList = ((MyUI) UI.getCurrent()).peopleService.getItemList();
TempPeopleContainer container = new TempPeopleContainer(myList);
table.setContainerDataSource(container);
table.setParent(myList.get(1), myList.get(0));

Blackberry: Drawing TableModel focus properly

I need help with drawing the focus of the selected row properly.
Currently if I select the first item of a category the separatorrow gets highlighted too. So how can I implement my custom focus drawing so that only the selected row gets focused/highlighted?
I am using the posted source code from here: Blackberry Tablemodel gets messed up when scrolling
I am using the Eclipse IDE from RIM and JRE 7.0.0
public class ProductsScreen extends MainScreen
{
private TableModel _tableModel;
private static final int ROW_HEIGHT = 40;
public ProductsScreen(MainCategory mc)
{
super(Manager.NO_VERTICAL_SCROLL | Manager.HORIZONTAL_SCROLL);
DBManager dbman = DBManager.getInstance();
AllProductByCategory[] products = null;
try {
products = dbman.getProducts(mc.getID().intValue());
} catch (DatabaseException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setTitle(mc.getName());
_tableModel = new TableModel();//(StringComparator.getInstance(true), 0);
if(products != null)
{
for(int i = 0; i < products.length; i++)
{
ViewableData[] data = products[i].getData().getViewableData();
for(int j = 0; j < data.length; j++)
{
_tableModel.addRow(new Object[] {products[i].getCategoryName(), data[j].getTitle2()});
}
}
}
RegionStyles style = new RegionStyles(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 1, 1), Border.STYLE_SOLID), null, null,
null, RegionStyles.ALIGN_LEFT, RegionStyles.ALIGN_TOP);
TableView tableView = new TableView(_tableModel);
final TableController tableController = new TableController(_tableModel, tableView);
tableController.setFocusPolicy(TableController.ROW_FOCUS);
tableController.setCommand(new Command(new CommandHandler()
{
public void execute(ReadOnlyCommandMetadata metadata, Object context)
{
}
}));
tableView.setController(tableController);
DataTemplate dataTemplate = new DataTemplate(tableView, 2, 2)
{
public Field[] getDataFields(int modelRowIndex)
{
final Object[] data = (Object[]) _tableModel.getRow(modelRowIndex);
Field[] fields = new Field[3];
String rowGroup = (String)data[0];
// we're in a new group if this is the very first row, or if this row's
// data[0] value is different from the last row's data[0] value
boolean isNewGroup = (modelRowIndex == 0) ||
(rowGroup.compareTo((String) ((Object[])_tableModel.getRow(modelRowIndex - 1))[0]) != 0);
if (isNewGroup) {
// make a separator row
fields[0] = new HeaderField((String)data[0],
Field.USE_ALL_WIDTH | Field.NON_FOCUSABLE);
} else {
// this is in the same group as the last product, so don't add anything here
fields[0] = new NullField();
}
// now, add the actual product information
fields[1] = new LabelField((String)data[1],
Field.USE_ALL_WIDTH | Field.FOCUSABLE | Field.USE_ALL_HEIGHT | DrawStyle.ELLIPSIS);
fields[2] = new BitmapField(Bitmap.getBitmapResource("img/bullet_arrow_right.png"));
return fields;
}
};
dataTemplate.createRegion(new XYRect(0, 0, 2, 1)); // group separator (maybe a null field)
dataTemplate.createRegion(new XYRect(0, 1, 1, 1)); // actual rows with product information
dataTemplate.createRegion(new XYRect(1, 1, 1, 1));
dataTemplate.setColumnProperties(0, new TemplateColumnProperties(95, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setColumnProperties(1, new TemplateColumnProperties(5, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setRowProperties(0, new TemplateRowProperties(ROW_HEIGHT)); // separator
dataTemplate.setRowProperties(1, new TemplateRowProperties(ROW_HEIGHT)); // product data
dataTemplate.useFixedHeight(false);
tableView.setDataTemplate(dataTemplate);
add(tableView);
}
}
SOLUTION:
I was able to solve the problem on my own with the following approach.
I just added a overridden LabelField as headerfield and didn't implement its focus drawing. So only the "subfields" get the focus drawn.
Maybe some people would implement it in another way (take a look at the answer from Nate) but it worked for me.
So, I didn't have time to fully integrate your new code sample, which has data model code that I don't have, and which appears to have added a DataTemplate column for a BitmapField. Hopefully, you can adapt what I have to reintegrate those changes.
I'm sure there's more than one way to do this, and I'm not claiming this method to be the highest performance. However, it seems to draw the focus as you would expect, without the separator row getting highlighted when the row directly under it is focused.
What I did was abandon the concept of using multiple regions, and just made my data template 1 row by 1 column. If you want, you can probably make it 1 row by 2 columns, where the column I don't show is the BitmapField.
But, what I did was to place a VerticalFieldManager in the first row in each new group/category. That VerticalFieldManager then contained a separator/header row, a separator field (just a horizontal line), and then the actual product row. If the row was not the first in the group/category, I would just return a simple Field, not a VerticalFieldManager with three Field objects inside it.
Then, I changed the TableController focus policy to FIELD_FOCUS, not ROW_FOCUS. This allows focus to be taken by the VerticalFieldManager, when we're on the first row in a new group/category. However, inside that manager, only the actual product row is focusable. The separator row is not focusable, and will therefore not be drawn with focus.
Here's the code that changed. The rest is the same as in the previous sample I gave you:
_tableController.setFocusPolicy(TableController.FIELD_FOCUS);
_tableView.setController(_tableController);
DataTemplate dataTemplate = new DataTemplate(_tableView, 1, 1) // 1 row now!
{
public Field[] getDataFields(int modelRowIndex)
{
final Object[] data = (Object[]) _tableModel.getRow(modelRowIndex);
String rowGroup = (String)data[0];
// we're in a new group if this is the very first row, or if this row's data[0] value is
// different from the last row's data[0] value
boolean isNewGroup = (modelRowIndex == 0) ||
(rowGroup.compareTo((String) ((Object[])_tableModel.getRow(modelRowIndex - 1))[0]) != 0);
if (isNewGroup) {
LabelField header = new LabelField((String)data[0], Field.USE_ALL_WIDTH | Field.NON_FOCUSABLE);
SeparatorField line = new SeparatorField(Field.USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.BLACK);
super.paint(g);
}
};
LabelField productRow = new LabelField((String)data[1],
Field.USE_ALL_WIDTH | Field.FOCUSABLE | DrawStyle.HCENTER);
VerticalFieldManager manager = new VerticalFieldManager(Field.USE_ALL_WIDTH | Field.FOCUSABLE |
Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR);
manager.add(header);
manager.add(line);
manager.add(productRow);
return new Field[] { manager };
} else {
return new Field[] { new LabelField((String)data[1],
Field.USE_ALL_WIDTH | Field.FOCUSABLE | DrawStyle.HCENTER) };
}
}
};
// create just one region, with one row and one full-width column
dataTemplate.createRegion(new XYRect(0, 0, 1, 1), _style); // may be a product row, or a product row + separator
dataTemplate.setColumnProperties(0, new TemplateColumnProperties(100, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setRowProperties(0, new TemplateRowProperties(2 * ROW_HEIGHT)); // max height if row + separator
_tableView.setDataTemplate(dataTemplate);
dataTemplate.useFixedHeight(false);
The scrolling is a little funny when you get down to the bottom of the page, but I'm pretty sure I've built VerticalFieldManager subclasses before that acted like lists, that needed some custom scroll handling ... if I get some time tomorrow, I'll try to add that in.
One step at a time, though ...

Blackberry Tablemodel gets messed up when scrolling

I want to implement a scrollable List which is sorted alphabetically.
As a reference I am using the Tree Screen sample which comes delivered with the Eclipse IDE.
I changed the datatemplate to fit my needs and it works like a charm until you want to scroll. The whole UI gets messed up and I don't know what to do. I'm using JRE 7.1 and the Blackberry Simulator 9860 7.0 (I've also tested it on a real device).
Does anybody know if this is a known issue or do I miss something?
package lifeApp;
import net.rim.device.api.command.Command;
import net.rim.device.api.command.CommandHandler;
import net.rim.device.api.command.ReadOnlyCommandMetadata;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.table.DataTemplate;
import net.rim.device.api.ui.component.table.RegionStyles;
import net.rim.device.api.ui.component.table.SortedTableModel;
import net.rim.device.api.ui.component.table.TableController;
import net.rim.device.api.ui.component.table.TableModel;
import net.rim.device.api.ui.component.table.TableView;
import net.rim.device.api.ui.component.table.TemplateColumnProperties;
import net.rim.device.api.ui.component.table.TemplateRowProperties;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.decor.Border;
import net.rim.device.api.ui.decor.BorderFactory;
import net.rim.device.api.util.StringComparator;
public class ProductsScreen extends MainScreen
{
private SortedTableModel _tableModel;
private static final int ROW_HEIGHT = 40;
public ProductsScreen()
{
super(Manager.NO_VERTICAL_SCROLL | Manager.HORIZONTAL_SCROLL);
setTitle("Alle Produkte A-Z");
add(new LabelField("BlackBerry Devices", LabelField.FIELD_HCENTER));
add(new SeparatorField());
_tableModel = new SortedTableModel(StringComparator.getInstance(true), 0);
_tableModel.addRow(new Object[] {"A", "Produkt1"});
_tableModel.addRow(new Object[] {"b", "Produkt2"});
_tableModel.addRow(new Object[] {"c", "Produkt3"});
_tableModel.addRow(new Object[] {"c", "Produkt4"});
_tableModel.addRow(new Object[] {"b", "Produkt5"});
_tableModel.addRow(new Object[] {"c", "Produkt6"});
_tableModel.addRow(new Object[] {"c", "Produkt7"});
_tableModel.addRow(new Object[] {"r", "Produkt8"});
_tableModel.addRow(new Object[] {"t", "Produkt9"});
_tableModel.addRow(new Object[] {"c", "Produkt10"});
_tableModel.addRow(new Object[] {"b", "Produkt11"});
_tableModel.addRow(new Object[] {"u", "Produkt12"});
_tableModel.addRow(new Object[] {"v", "Produkt13"});
_tableModel.addRow(new Object[] {"t", "Produkt14"});
_tableModel.addRow(new Object[] {"c", "Produkt15"});
_tableModel.addRow(new Object[] {"b", "Produkt16"});
_tableModel.addRow(new Object[] {"u", "Produkt17"});
_tableModel.addRow(new Object[] {"v", "Produkt18"});
RegionStyles style = new RegionStyles(BorderFactory.createSimpleBorder(new XYEdges(1, 1, 1, 1), Border.STYLE_SOLID), null, null,
null, RegionStyles.ALIGN_LEFT, RegionStyles.ALIGN_TOP);
TableView tableView = new TableView(_tableModel);
TableController tableController = new TableController(_tableModel, tableView);
tableController.setFocusPolicy(TableController.ROW_FOCUS);
tableController.setCommand(new Command(new CommandHandler()
{
public void execute(ReadOnlyCommandMetadata metadata, Object context)
{
Dialog.alert("Command Executed");
}
}));
tableView.setController(tableController);
DataTemplate dataTemplate = new DataTemplate(tableView, 1, 1)
{
/**
* #see DataTemplate#getDataFields(int)
*/
public Field[] getDataFields(int modelRowIndex)
{
final Object[] data = (Object[]) ((TableModel) getView().getModel()).getRow(modelRowIndex);
Field[] fields = new Field[1];
fields[0] = new LabelField((String)data[1], Field.USE_ALL_WIDTH | Field.FOCUSABLE | DrawStyle.HCENTER);
return fields;
}
};
dataTemplate.createRegion(new XYRect(0, 0, 1, 1), style);
dataTemplate.setColumnProperties(0, new TemplateColumnProperties(100, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setRowProperties(0, new TemplateRowProperties(ROW_HEIGHT));
tableView.setDataTemplate(dataTemplate);
dataTemplate.useFixedHeight(true);
add(tableView);
}
}
Well, I loaded up the JDE 7.1 UI/TableAndListDemo sample app, and ran it on the JDE 9900.
That sample (unmodified by me) exhibits the exact same screwy behaviour as the code you posted.
So, unfortunately, I would say that either there is a bug, or a valid example of how to use the relatively new SortedTableModel has not been produced (I couldn't find any better ones).
Of note: if you remove the sorting, and simply replace SortedTableModel with TableModel, the visual corruption goes away for me. Of course, you lose the important feature of the sorting, and the grouping (column 0 in your table model).
Another option would be to implement the sorting behaviour yourself. Sorting the data outside of the TableModel is undesirable, but also not too difficult. Then, you could add an extra row to the repeating pattern, as a placeholder for the separator row that you currently have showing the single character (the sort criterion). You would also change the data template to not be fixed height.
Also, in the data template, you would define a region that can hold the separator row. Whether or not that region will show anything or not depends on whether the data row to follow has the same single character as the last row, or not. So, here's what the code might look like
DataTemplate dataTemplate = new DataTemplate(tableView, 2, 1) // 2 "rows", not 1
{
public Field[] getDataFields(int modelRowIndex)
{
final Object[] data = (Object[]) _tableModel.getRow(modelRowIndex);
Field[] fields = new Field[2];
String rowGroup = (String)data[0];
// we're in a new group if this is the very first row, or if this row's
// data[0] value is different from the last row's data[0] value
boolean isNewGroup = (modelRowIndex == 0) ||
(rowGroup.compareTo((String) ((Object[])_tableModel.getRow(modelRowIndex - 1))[0]) != 0);
if (isNewGroup) {
// make a separator row
fields[0] = new LabelField((String)data[0],
Field.USE_ALL_WIDTH | Field.NON_FOCUSABLE);
} else {
// this is in the same group as the last product, so don't add anything here
fields[0] = new NullField();
}
// now, add the actual product information
fields[1] = new LabelField((String)data[1],
Field.USE_ALL_WIDTH | Field.FOCUSABLE | DrawStyle.HCENTER);
return fields;
}
};
dataTemplate.createRegion(new XYRect(0, 0, 1, 1), style); // group separator (maybe a null field)
dataTemplate.createRegion(new XYRect(0, 1, 1, 1), style); // actual rows with product information
dataTemplate.setColumnProperties(0, new TemplateColumnProperties(100, TemplateColumnProperties.PERCENTAGE_WIDTH));
dataTemplate.setRowProperties(0, new TemplateRowProperties(ROW_HEIGHT)); // separator
dataTemplate.setRowProperties(1, new TemplateRowProperties(ROW_HEIGHT)); // product data
dataTemplate.useFixedHeight(false);
In the above code, I chose to make the separator rows the same height and style as the product data rows. Of course, you could change that if you like.
One problem that this still doesn't solve is that of focus drawing. When you highlight the first row under the separator row, it draws focus on the product row, and the separator row above it.
You may need to implement some custom focus drawing. I'll leave that for the next question ... not sure if you even want to go this route. Hopefully I'm wrong, but it kind of looks like a bug in the RIM libraries to me :(

Align field to right in grid layout in blackberry

I want my application to align two field, one to left and other to extreme left of the screen. For that i am using GridLayoutManager class. Here is my code
GridFieldManager gridFieldManager = new GridFieldManager(2,2, GridFieldManager.PREFERRED_SIZE_WITH_MAXIMUM);
gridFieldManager.add(new ButtonField("Button One"), Field.FIELD_HCENTER);
gridFieldManager.add(new ButtonField("Button Two"), Field.FIELD_RIGHT);
gridFieldManager.add(new ButtonField("HC", Field.FIELD_HCENTER));
gridFieldManager.add(new ButtonField("RT", Field.FIELD_RIGHT));
add(gridFieldManager);
And, here is my output in simulator
Can anyone please help me to align the Button Two to the extreme right of the screen ? Any help will be appreciated.
Basically it's all a matter of alignment flags and grid's column properties.
Changing the GridFieldManager style to Manager.USE_ALL_WIDTH and setting column properties to GridFieldManager.AUTO_SIZE makes all the available space to be divided evently among the two columns.
gridFieldManager.setColumnProperty(0, GridFieldManager.AUTO_SIZE, 0);
gridFieldManager.setColumnProperty(1, GridFieldManager.AUTO_SIZE, 0);
The following code snippet
GridFieldManager gridFieldManager = new GridFieldManager(2,2, Manager.USE_ALL_WIDTH);
gridFieldManager.setColumnProperty(0, GridFieldManager.AUTO_SIZE, 0);
gridFieldManager.setColumnProperty(1, GridFieldManager.AUTO_SIZE, 0);
gridFieldManager.add(new ButtonField("Button One"), Field.FIELD_LEFT);
gridFieldManager.add(new ButtonField("Button Two"), Field.FIELD_RIGHT);
gridFieldManager.add(new ButtonField("HC"), Field.FIELD_LEFT);
gridFieldManager.add(new ButtonField("RT"), Field.FIELD_RIGHT);
add(gridFieldManager);
produces
This slightly modified code snippet
GridFieldManager gridFieldManager = new GridFieldManager(1,2, Manager.USE_ALL_WIDTH);
gridFieldManager.setColumnProperty(0, GridFieldManager.AUTO_SIZE, 0);
gridFieldManager.setColumnProperty(1, GridFieldManager.AUTO_SIZE, 0);
VerticalFieldManager vfmLeft = new VerticalFieldManager();
vfmLeft.add(new ButtonField("Button One", Field.FIELD_HCENTER));
vfmLeft.add(new ButtonField("HC", Field.FIELD_HCENTER));
gridFieldManager.add(vfmLeft, Field.FIELD_LEFT);
VerticalFieldManager vfmRight = new VerticalFieldManager();
vfmRight.add(new ButtonField("Button Two", Field.FIELD_HCENTER));
vfmRight.add(new ButtonField("RT", Field.FIELD_HCENTER));
gridFieldManager.add(vfmRight, Field.FIELD_RIGHT);
add(gridFieldManager);
produces
Finally, to illustrate what I said previously about the available space being divided evently among the two columns, the following code snippet
GridFieldManager gridFieldManager = new GridFieldManager(1,2, Manager.USE_ALL_WIDTH | Manager.USE_ALL_HEIGHT);
gridFieldManager.setColumnProperty(0, GridFieldManager.AUTO_SIZE, 0);
gridFieldManager.setColumnProperty(1, GridFieldManager.AUTO_SIZE, 0);
gridFieldManager.setRowProperty(0, GridFieldManager.AUTO_SIZE, 0);
VerticalFieldManager vfmLeft = new VerticalFieldManager(Manager.USE_ALL_WIDTH | Manager.USE_ALL_HEIGHT);
vfmLeft.setBackground(BackgroundFactory.createSolidBackground(Color.CYAN));
gridFieldManager.add(vfmLeft);
VerticalFieldManager vfmRight = new VerticalFieldManager(Manager.USE_ALL_WIDTH | Manager.USE_ALL_HEIGHT);
vfmRight.setBackground(BackgroundFactory.createSolidBackground(Color.GRAY));
gridFieldManager.add(vfmRight);
add(gridFieldManager);
produces two columns of equal size.
Please use this following class.
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.container.HorizontalFieldManager;
public class HFMLeftFieldRightField extends HorizontalFieldManager {
private Field leftField;
private Field rightField;
private final static int TOP_MARGIN = 0;
private final static int LEFT_MARGIN = 30;
public HFMLeftFieldRightField() {
super(USE_ALL_WIDTH);
}
public HFMLeftFieldRightField(boolean isQatari) {
super(USE_ALL_WIDTH | Field.FIELD_LEFT);
}
public void sublayout(int maxWidth, int maxHeight) {
super.sublayout(maxWidth, maxHeight);
int width = getWidth();
if (rightField != null) {
int x = width - rightField.getWidth() - LEFT_MARGIN;
int y = TOP_MARGIN;
setPositionChild(rightField, x, y);
}
if (leftField != null) {
int y = TOP_MARGIN+rightField.getHeight()/5;
int x = LEFT_MARGIN;
setPositionChild(leftField, 0, y);
}
setExtent(maxWidth, rightField.getHeight() + TOP_MARGIN * 2);
}
public void setLeftButton(Field leftField) {
this.leftField = leftField;
super.add(leftField);
}
public void setRightButton(Field rightField) {
this.rightField = rightField;
super.add(rightField);
}
}
And add field this way.
HFMLeftFieldRightField hfm = new HFMLeftFieldRightField();
hfm.setLeftButton(new EditField("Left"));
hfm.setRightButton(new EditField("Right"));
add(hfm);
More detail http://keraisureshvblackberry.blogspot.in/2012/02/there-are-very-common-there-there-are.html
Hope helpfull..
It seems like you should use JustifiedHorizontalFieldManager instead of GridFieldManager. JustifiedHorizontalFieldManager is not a standard manager included in BlackBerry SDK, but a member of a set of UI components released by RIM later to help developers build more rich UI Interfaces. You have to download the code from here, add it to your proyect and then include the following line:
JustifiedHorizontalFieldManager justifiedManager = new JustifiedHorizontalFieldManager(buttonOne, buttonTwo, false, USE_ALL_WIDTH );
Change the style parameter of your gridFieldManager constructor to
GridFieldManager.USE_ALL_WIDTH
It should be like this
GridFieldManager gridFieldManager = new GridFieldManager(2,2,GridFieldManager.USE_ALL_WIDTH );

Resources