Search code examples
javaeclipseparentrcpcomposite

Eclipse RCP how to get composite parent


I want to create tableviewer in RCP but I don't know how to get "Composite parent". I have this code :

@PostConstruct
public void createComposite(Composite parent) {
    Books.generateBooks();
    Map<String, Books> allBooks = Books.returnAllBooks();
    List<String> booksList = new ArrayList<String>(allBooks.keySet());

    tableViewer = new TableViewer(parent);

    for(int i=0; i<booksList.size(); i++) {
        tableViewer.add(booksList.get(i));
    }

    tableViewer.addDoubleClickListener(new IDoubleClickListener() {
        @Override
        public void doubleClick(DoubleClickEvent event) {
            IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
            if (selection.isEmpty()) return;
            BibliotekaSzczegolyPart.createComposite(selection.getFirstElement().toString());
        }
    });
    tableViewer.getTable().setLayoutData(new GridData(GridData.FILL));
}

It creates table view in my part, and add DoubleClickListener in table positions. Now I want to create function createComposite in another class which I want to activate after double click but then I don't have "Composite parent" because it is not @PostConstruct. How to get it?


Solution

  • The best way to do this is to use the event broker to send a event that the other part can listen for. That way you don't need a reference to the other part.

    To send an event:

    @Inject
    IEventBroker eventBroker;
    
    String value = .... value you want to send (doesn't have to be a string)
    
    eventBroker.post("/my/topic", value);
    

    To listen for the event include a method like this in the class that wants to listen (assumes the class is created by injection):

    @Inject
    @Optional
    public void event(@UIEventTopic("/my/topic") final String value)
    {
      if (value != null) {
        // TODO Handle value
      }
    }
    

    You may get a call to the method with a value set to null while the part is being initialized so check for that.

    The method name can be anything you like.

    @UIEventTopic forces the event to arrive on the UI thread. Use @EventTopic if you don't care about the thread.

    The topic name can be whatever you choose but it must contain / separators as shown.

    More detail in this tutorial.