Access method from current UI in Vaadin

2019-07-30 00:21发布

问题:

i'm currently working on a Java Web Application in Vaadin.

I want to access a getter method, which is located in my LoginUI, from another class.

UI.getCurrent() successfully returns the current Thread (LoginUI).

Which methods do i need to call to achieve this?

Thank you in advance.

回答1:

UI.getCurrent() is not thread safe. Instead I recommend you the following pattern.

public class MyView extends VerticalLayout implements View {

    private UI ui;

    @Override
    public onAttach() {
        ui = getUI();
        ...
    }

...

    public updateMe(..) {
        ...
        try {
           ui.access( ... do updates ... );
        } catch (UIDetachedException e) {
           // Do nothing, this exception is thrown if Browser is closed
        }
    }
}

Explained. Store UI reference when your View is attached. And write a method that updates the view as you need do the ui.access() there. Call this method to do the updates instead do doing UI.getCurrent() in the thread.

This is frequently asked topic, there is more specific case question about the same thing also here vaadin 10 - Push - Label won't update