我想在鼠标单击事件中从ContentPanel删除所有元素,然后添加新元素。使用removeAll()方法可以正常工作,这将删除所有现有组件。但是,当我想添加一个新组件时,不会添加它。

最佳答案

也许像这样,我省略了点击处理程序,但是您应该从中得到灵感。

private ContentPanel contentPanel;

public SwapScreen() {
 contentPanel = new ContentPanel();
 add(contentPanel);
}

public void swap1() {

   /*This should be split into a separate
    method and called only once to avoid recreating them.*/
   field1 = new TextField<String>();
   contentPanel.add(field1);

   field2 = new TextField<String>();
   contentPanel.add(field2);

  this.layout(true);
}

public void swap2() {

   /*This should be split into a separate
    method and called only once to avoid recreating them.*/
   anotherField1 = new TextField<String>();
   contentPanel.add(anotherField1);

   anotherField2 = new TextField<String>();
   contentPanel.add(anotherField2);

   this.layout(true);
}


最重要的部分是this.layout(true)强制其刷新布局,

07-27 13:48