发生这种情况是因为当您将另一个组件添加到 FlowLayout 时,它会调整大小,从而增加其自身的高度,从而将底部组件推到可见区域下方。代码中没有任何内容可以缩小中心组件,从而使底部组件保持在原来的位置。
另一件事是,您将 FitLayout 用于包含 3 个组件的 contentPanel,FitLayout 用于内部只有一个组件的容器,该组件应该填充其父级。
您需要考虑以下事项:
1) 使用 RowLayout,它可以更好地控制组件的布局方式
2) 决定您愿意在哪个组件上放置垂直滚动条,因为您要动态添加组件。
对于您当前的要求,以下代码应该足够了:
public void onModuleLoad() {
final Viewport viewport = new Viewport();
viewport.setLayout(new FitLayout());
// final ContentPanel contentPanel = new ContentPanel(new FlowLayout());
// contentPanel.setHeaderVisible(false);
final LayoutContainer topContainer = new LayoutContainer(
new FlowLayout());
final Button buttonOne = new Button("Top:One");
topContainer.add(buttonOne);
// contentPanel.setTopComponent(topContainer);
final LayoutContainer centerPanel = new LayoutContainer(new FitLayout());
centerPanel.add(new Button("Center"));
// contentPanel.add(centerPanel);
final LayoutContainer botPanel = new LayoutContainer(new FlowLayout());
botPanel.add(new Button("Bottom"));
// contentPanel.setBottomComponent(botPanel);
final ContentPanel panel = new ContentPanel();
panel.setHeaderVisible(false);
panel.setLayout(new RowLayout(Orientation.VERTICAL));
panel.add(topContainer, new RowData(1, -1, new Margins(4)));
panel.add(centerPanel, new RowData(1, 1, new Margins(0, 4, 0, 4)));
panel.add(botPanel, new RowData(1, -1, new Margins(4)));
viewport.add(panel, new FlowData(10));
RootPanel.get().add(viewport);
// Later, add a second button to the topComponent ...
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
final Button buttonTwo = new Button("Top:Two");
topContainer.add(buttonTwo); // Doesn't show up at first.
panel.layout(true);
}
});
}