tags:

views:

335

answers:

1

I have created some classes in which it create a bunch of widgets (e.g. label, textbox). I want to create the widget on the fly and add it to a panel. How can I do that.

+5  A: 

Assuming you use HorizontalPanel, VerticalPanel, FlowPanel or some other panel with an add(Wiget) method, you would simply invoke add(myWidget);

final VerticalPanel panel = new VerticalPanel();

final Button sendButton = new Button("Add widget");
panel.add(sendButton);
sendButton.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
     panel.add(new Label(new Date().toString()));
    }
});

RootPanel.get().add(panel);

An alternative may be use the setVisible(boolean) to show and hide widgets instead of adding and removing them.

final VerticalPanel panel = new VerticalPanel();

final Button sendButton = new Button("Toggle visibility");
panel.add(sendButton);

final Label label = new Label(new Date().toString());
panel.add(label);

sendButton.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
     label.setVisible(!label.isVisible());
    }
});

RootPanel.get().add(panel);
Fedearne