Creating components as static factory style (Singl

2019-07-24 19:46发布

问题:

I would like to create custom Window using static factory style (or with singleton pattern).

public class MyWindow extends CustomComponent {
private static Window window;
private static MyWindow instance;

public static MyWindow getInstance() {
    if (instance == null) {
        instance = new MyWindow();
    }
    return instance;
}

public void show() {
    UI.getCurrent().addWindow(window);
}

private MyWindow() {
    CustomLayout layout = new CustomLayout("My HTML Layout");
    window = new Window("My Window");
    window.center();
    window.setWidth("615px");
    window.setModal(true);
    window.setResizable(false);
    window.setClosable(true);
    window.setContent(layout);
}
}

And call as MyWindow.getInstance().show(); First time calling was ok but after closing this window and while reopened , I got below error logs at my console.

Jul 23, 2014 3:42:39 AM com.vaadin.server.DefaultErrorHandler doDefault
SEVERE: 
java.lang.IllegalStateException: com.vaadin.ui.Window already has a parent.
at com.vaadin.ui.AbstractComponent.setParent(AbstractComponent.java:469)
at com.vaadin.ui.Window.setParent(Window.java:155)
at com.vaadin.ui.UI.attachWindow(UI.java:501)
at com.vaadin.ui.UI.addWindow(UI.java:490)

So , how can I use customize Windows with static factory style and how to hide and show Windows ?

回答1:

I think the easiest way is to create a new Window Object everytime you call the show() method.



回答2:

The error says that your Window already have a parent. It means that it wasn't removed when you closed it. It is actually weird I've never had that error before. But you can try this if you want:

 window.addCloseListener(new CloseListener() {

  @Override
  public void windowClose(CloseEvent e) {
    AbstractSingleComponentContainer.removeFromParent(subwindow);
  }
});

This should resolve your problem.