Почему я не могу снова установить содержимое после того, как sh веб-страница была удалена в Vaadin? - PullRequest
0 голосов
/ 09 мая 2020

У меня странная проблема. Мое веб-приложение работает, так как оно не удаляет текст / числа из текстовых полей и не сбрасывает флажки, когда я обновляю sh веб-страницу из веб-браузера.

Но когда я обновляю sh веб-страницу тогда у меня возникла проблема:

java.lang.IllegalStateException: Can't move a node from one state tree to another. If this is intentional, first remove the node from its current state tree by calling removeFromTree
java.lang.IllegalStateException: Unregistered node was not found based on its id. The tree is most likely corrupted.

и

Assertion error: No child node found with id 28
Assertion error: Node 3 is already registered

Так почему я не могу снова установить контент после того, как я освободил sh веб-страницу в Vaadin? Я использую Vaadin 14. Если я не обновляю sh веб-страницу, я могу изменять содержимое столько, сколько захочу. Но пока я не обновляю sh веб-страницу, я не получу сообщения об ошибке.

Обратите внимание, что у меня включен @PreserveOnRefresh. Без этого у меня не будет ошибок. Но тогда текст / значения и вся информация исчезнут, когда я обновлю sh страницу.

Вот мой код.

@Route("")
@Viewport("width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes, viewport-fit=cover")
@PreserveOnRefresh
public class MainView extends AppLayout {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public MainView() {

        // Get the components
        BuildPredictValidateTemplate buildPredictValidateTemplate = new BuildPredictValidateTemplate();
        LoadExportTemplate loadExportTemplate = new LoadExportTemplate();

        // Create logo and drawer
        Image barImage = new Image("img/barImage.png", "Fisherfaces Logo");
        barImage.setHeight("55px");
        addToNavbar(new DrawerToggle(), barImage);

        // Create tabs and add listeners to them
        Tab buildPredictValidate = new Tab("Build & Predict & Validate");
        buildPredictValidate.getElement().addEventListener("click", e -> {
            setContent(buildPredictValidateTemplate.getBuildButtonPredictButtonValidateButtonTextArea());
        });
        Tab loadExport = new Tab("Load & Export");
        loadExport.getElement().addEventListener("click", e -> {
            setContent(loadExportTemplate.getSubjectCounterExportButtonUploaders());
        });

        // Add them and place them as vertical
        Tabs tabs = new Tabs(buildPredictValidate, loadExport);
        tabs.setOrientation(Tabs.Orientation.VERTICAL);
        addToDrawer(tabs);

    }
}

и

@Data
//@Component
public class BuildPredictValidateTemplate {

    private VerticalLayout buildButtonPredictButtonValidateButtonTextArea;

    public BuildPredictValidateTemplate() {

        // Create the complete form layout
        buildButtonPredictButtonValidateButtonTextArea = createBuildButtonPredictButtonValidateButtonTextArea();

    }

    private VerticalLayout createBuildButtonPredictButtonValidateButtonTextArea() {

        // Text area that works like a terminal
        TextArea textTerminal = new TextArea();
        textTerminal.setPlaceholder("");
        textTerminal.setWidthFull();
        textTerminal.setHeightFull();

        // Progressbar
        ProgressBar progressBar = new ProgressBar();
        progressBar.setValue(0);

        // Buttons for Builing, Predicting and Validate
        Button build = new Button("Build");
        build.addClickListener(e -> {
            System.out.println("Building");
        });
        Button predict = new Button("Predict");
        predict.addClickListener(e -> {
            System.out.println("Predicting");
        });
        Button validate = new Button("Validate");
        validate.addClickListener(e -> {
            System.out.println("Validating");
        });

        // Uploader for prediction
        //Upload upload = new PictureUpload().getUpload();

        // Add them all now
        HorizontalLayout horizon = new HorizontalLayout(build, validate, predict);
        return new VerticalLayout(horizon, progressBar, textTerminal);

    }

}

А также

@Data
//@Component
public class LoadExportTemplate {

    private VerticalLayout subjectCounterExportButtonUploaders;

    public LoadExportTemplate() {
        // Create layout for the uploads
        VerticalLayout uploadsLayout = new VerticalLayout();

        // Create subject counter for how many uploaders we should have
        NumberField subjectCounter = createSubjectCounter(uploadsLayout);

        // Create layout for holding subject counter, export button and uploaders
        subjectCounterExportButtonUploaders = createLayoutForSubjectCounterExportButtonUploaders(subjectCounter, uploadsLayout);

    }

    private VerticalLayout createLayoutForSubjectCounterExportButtonUploaders(NumberField subjectCounter, VerticalLayout uploadsLayout) {
        // Create SubjectCounter and ExportButton on a row
        Button exportButton = new Button("Export to MATLAB code");
        exportButton.addClickListener(e -> {
            System.out.println("Exported to MATLAB code.");
        });
        HorizontalLayout layoutHorizon = new HorizontalLayout(subjectCounter, exportButton);

        // Add the uploaders under the horizontal layout
        return new VerticalLayout(layoutHorizon, uploadsLayout);
    }

    private NumberField createSubjectCounter(VerticalLayout uploadsLayout) {
        NumberField subjectCounter = new NumberField();
        subjectCounter.setValue(1d);
        subjectCounter.setHasControls(true);
        subjectCounter.setMin(1);
        subjectCounter.addValueChangeListener(e-> {
            // First clear, then fill with new uploaders
            uploadsLayout.removeAll();
            for(Double i = 0.0; i < e.getValue(); i++) {
                PictureUpload pictureUpload = new PictureUpload();
                uploadsLayout.add(pictureUpload.getUpload());
            }
        });
        // Add one to begin with
        //PictureUpload pictureUpload = new PictureUpload();
        //uploadsLayout.add(pictureUpload.getUpload());

        return subjectCounter;

    }
}

1 Ответ

1 голос
/ 09 мая 2020

Я считаю, что это ошибка в Ваадине, по крайней мере, это не то, чего я ожидал.

Я создал для нее проблему https://github.com/vaadin/flow/issues/8286

Изменить:

В качестве временного решения вы можете вместо этого переключить видимость. Но для этого вам потребуется добавить все компоненты, например, в Div, и установить их в качестве содержимого.

Например, setContent(new Div(component1, component2));

Затем, щелкнув вкладку, вам придется скрыть все компоненты, кроме выбранного, например,

getContent().getChildren().forEach(component -> {
    boolean visible = component.equals(theComponentIWantToShow);
    component.setVisible(visible);
});
...