Search code examples
javaeclipsercp

How to point to newly added element using an action to a tableviewer?


Action add = new Action("Add Values") {
        @Override
        public void run() {
            Bike bike = new Bike();
             bike.setName("BMW");
            tableViewer.refresh();
        }
    };

I have a table viewer and show the bike names in the column .. If I add a new element using the action I have my selection to the top most element instead of newly added element . How can I achieve this .

I have a list in my setinput which calls treeviewercontentprovider

private static class TreeContentProvider implements ITreeContentProvider {
    public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
      }

    public void dispose() {
    }


    public Object[] getElements(Object inputElement) {
        return getChildren(inputElement);
    }

    public Object[] getChildren(Object parentElement) {

        if (parentElement instanceof Object[]) {
            return (Object[]) parentElement;
        }

        if (parentElement instanceof Collection) {
            return ((Collection) parentElement).toArray();
            }

        return new Object[0];
      }


    public Object getParent(Object element) {
            return null;
     }

    public boolean hasChildren(Object element) {
          return false;
      }
    }

Solution

  • I achieved the requirement using this code added to action. setselection to the new element points to the newly added element after adding to the table.

    Action add = new Action("Add Values") {
        @Override
        public void run() {
            Bike bike = new Bike();
             bike.setName("BMW");
            tableViewer.refresh();
    
            tableViewer.setSelection(new StructuredSelection(bike));
        }
    };