Search code examples
javaswteclipse-rcpjfacetableviewer

How to populate TableViewer in a vertical fashion


I have a TreeViewer which contains some nodes which each node has some attributes with their corresponding values. I have also a TableViewer to show the attributes and their corresponding values of the selected node from the TreeViewer. In the table there are only 2 columns, one showing the attribute name (on the left) and the other one showing the value of that attribute (on the right).

I have the attributes and values in a HashMap(attributes, value)

But since each node is representing one object, the call to AttributeLabelProvider (implements ITableLabelProvider) method getColumnText(Object element, int columnIndex) only happens once. But I need to create 10 rows to show all the 10 attributes on the attribute column and their values on the right column.

tableViewer.setInput(selectedNode);
// The following is where I have implemented IStructuredContentProvider to use as my content provider
@Override
public Object[] getElements(Object inputElement) {
    TreeNode TN = (TreeNode) inputElement;
    return TN.getAttributes().values().toArray(); // ***
}

*** here I can only pass either keySet() or values() because my attributes are in a HashMap.

Thanks in advance :)


Solution

  • I found one solution, but I am not sure if this is safe. This will return both the values and the keys in an array of Objects[]:

    @Override
    public Object[] getElements(Object inputElement) {
        TreeNode TN = (TreeNode) inputElement;
        return TN.getAttributes().entrySet().toArray();
    }
    

    Then I used the following in ITableLabelProvider.getColumnText() for columns one and two:

    col.setLabelProvider(new ColumnLabelProvider() {   // Column 1 (contains the keys)
            @Override
            public String getText(Object element) {
                String str = element.toString();
                String[] parts = str.split("=");
                return parts[0];
            }
        });
    
    col.setLabelProvider(new ColumnLabelProvider() {  // Column 2 (Contains the values)
            @Override
            public String getText(Object element) {
                String str = element.toString();
                String[] parts = str.split("=");
                return parts[1];
            }
        });