Search code examples
javaeclipsereferencercp

Eclipse RCP get part instance


I am trying to get reference to part which is connected to Java class. I can use

`@PostConstruct
public void createComposite(Composite parent) {

}`

and then "parent" variable is what I need. But I want to have another method. I am trying to add static variable to save it like that:

public class BibliotekaZmianyPart {
private static Label label;
private static Button button;
private static Composite part;

@PostConstruct
public void createComposite(Composite parent) {
    part = parent;
}

public static void editBook() {
    GridLayout layout = new GridLayout(2, false);
    part.setLayout(layout);
    label = new Label(part, SWT.NONE);
    label.setText("A label");
    button = new Button(part, SWT.PUSH);
    button.setText("Press Me");
}}

and then "part" should be variable which I need - but it doesn't work.


Solution

  • You can't have a static method like that referencing instance variables.

    If you want to reference an existing part from another part you use the EPartService to find the part:

    @Inject
    EPartService partService;
    
    
    MPart mpart = partService.findPart("part id");
    
    BibliotekaZmianyPart part = (BibliotekaZmianyPart)mpart.getObject();
    
    part.editBook();   // Using non-static 'editBook'
    

    If the part is not already open you use the part service showPart method:

    MPart mpart = partService.showPart("part id", PartState.ACTIVATE);
    
    BibliotekaZmianyPart part = (BibliotekaZmianyPart)mpart.getObject();
    
    part.editBook();
    

    So your class would be:

    public class BibliotekaZmianyPart {
    private Label label;
    private Button button;
    private Composite part;
    
    @PostConstruct
    public void createComposite(Composite parent) {
        part = parent;
    }
    
    public void editBook() {
        GridLayout layout = new GridLayout(2, false);
        part.setLayout(layout);
        label = new Label(part, SWT.NONE);
        label.setText("A label");
        button = new Button(part, SWT.PUSH);
        button.setText("Press Me");
    
        // You probably need to call layout on the part
        part.layout();
    }}