您的面板subVP
未被添加到任何內容,並且當box
被添加到subVP
時,它將從mainVP
中刪除。小工具一次只能在一個地方。
-
(添加詳細張貼評論)
這是一個小部件是如何工作的基本假設的一部分 - 它是不是一個「郵票」,可以在放頁面,而是代表一個或多個DOM元素,並將其包裝起來以便於使用和重用。每個小部件都公開了一些您可以偵聽的事件處理程序,以及更改小部件外觀的方法。
試想一下,如果你有兩個頁面上的按鈕,你需要他們做了同樣的事情。在查看頁面時,顯然有兩個按鈕,雖然它們看起來相同並導致相同的操作,但它們不是同一件事。
考慮一下該按鈕可以在內部工作 - 可以說,它有一個檢查,看看是否鼠標懸停,如果是這樣顯示工具提示,或改變顏色。如果同一個小部件在兩個地方渲染,現在都會得到此更改。
從API端:Widget
有一個方法getParent()
,它返回父窗口小部件。如果你能在一個時間窗口小部件添加到不止一個地方,無論是getParent()
將是不可能的,否則就需要返回一個列表。
面板同樣有indexOf
,但如果你可以添加小部件多個父,這也將遵循您可以在同一窗口小部件添加到同父多次 - 會是什麼indexOf
回報呢?
最後,執行實現這一目標。從的Javadoc Panel.add
:
/**
* Adds a child widget.
*
* <p>
* <b>How to Override this Method</b>
* </p>
* <p>
* There are several important things that must take place in the correct
* order to properly add or insert a Widget to a Panel. Not all of these steps
* will be relevant to every Panel, but all of the steps must be considered.
* <ol>
* <li><b>Validate:</b> Perform any sanity checks to ensure the Panel can
* accept a new Widget. Examples: checking for a valid index on insertion;
* checking that the Panel is not full if there is a max capacity.</li>
* <li><b>Adjust for Reinsertion:</b> Some Panels need to handle the case
* where the Widget is already a child of this Panel. Example: when performing
* a reinsert, the index might need to be adjusted to account for the Widget's
* removal. See {@link ComplexPanel#adjustIndex(Widget, int)}.</li>
* <li><b>Detach Child:</b> Remove the Widget from its existing parent, if
* any. Most Panels will simply call {@link Widget#removeFromParent()} on the
* Widget.</li>
* <li><b>Logical Attach:</b> Any state variables of the Panel should be
* updated to reflect the addition of the new Widget. Example: the Widget is
* added to the Panel's {@link WidgetCollection} at the appropriate index.</li>
* <li><b>Physical Attach:</b> The Widget's Element must be physically
* attached to the Panel's Element, either directly or indirectly.</li>
* <li><b>Adopt:</b> Call {@link #adopt(Widget)} to finalize the add as the
* very last step.</li>
* </ol>
* </p>
*
* @param child the widget to be added
* @throws UnsupportedOperationException if this method is not supported (most
* often this means that a specific overload must be called)
* @see HasWidgets#add(Widget)
*/
public void add(Widget child)
最後,在GWT大多數面板使用的默認實現基本上是這樣,在它的心臟(ComplexPanel.add
):
// Detach new child.
child.removeFromParent();
// Logical attach.
getChildren().add(child);
// Physical attach.
DOM.appendChild(container, child.getElement());
// Adopt.
adopt(child);
還有其他的實現方式爲好,但他們主要歸結於此,以符合Panel
中概述的指導方針。
感謝colin..I想知道如何小部件正從mainVP去除內部... –
更新了一些背景思想和實現了答案,希望它幫助。 –