In order to have different component hierarchies in your markup and
Java, you need an indirection; make two Panels for your component.
Then conditionally add one panel or the other to the enclosing component.

The following example displays either an external link or some text.

NestedLinkPanel.java:

public class NestedLinkPanel extends Panel {

   public NestedLinkPanel(String name, IModel model) {
       super(name, model);
       add(new ExternalLink("myLink", "http://google.com").add(new Label("label", "bar")));
       add(new Label("foo", "Hello, World!"));
   }
}

NestedLinkPanel.html:

<html>
<body>
<wicket:panel>
<a href="#" wicket:id="myLink"><span wicket:id="label">bar</span></a>
<span wicket:id="foo">message goes here</span>
</wicket:panel>
</body>
</html>

NestedStaticTextPanel.java:

public class NestedStaticTextPanel extends Panel {
   public NestedStaticTextPanel(String name, IModel model) {
       super(name, model);
       add(new Label("label", "bar"));
       add(new Label("foo", "Hello, World!"));
   }
}

NestedStaticTextPanel.html:

<html>
<body>
<wicket:panel>
<span wicket:id="label">bar</span>
<span wicket:id="foo">message goes here</span>
</wicket:panel>
</body>
</html>

MyPage.html

<html>
<body>
<span wicket:id="panel">x</span>
</body>
</html>

MyPage.java

public class MyPage extends WebPage {
   public MyPage() {
      Object myModel = // ...
      if(modelObject instanceof List) {
          panel = new NestedStaticTextPanel("panel", null);
      } else {
          panel = new NestedLinkPanel("panel", model);
      }
      item.add(panel);
   }
}

Another approach is to add all components you might want to display, and make all invisible (using Component.setVisible()) but the one you want to show. This usually takes less code, but it is also much less flexible and not suited for cases where you have a lot of possible components or creating the components is expensive.

Panels can be used with ListView, GridView and similar components. It is also possible to create Forms with dynamic elements with the help of panels.

  • No labels