Fixes a bug in MenuBar where the selectedItem was not set to null when an item is removed or clearItems is called. This could result in a JS null pointer exception if garbage collection runs because we try to access an element that no longer has any references to it. Issue: 2178 Patch by: jlabanca Review by: bruce git-svn-id: https://google-web-toolkit.googlecode.com/svn/trunk@2115 8db76d5a-ed1c-0410-87a9-c151d255dfc7
diff --git a/user/src/com/google/gwt/user/client/ui/MenuBar.java b/user/src/com/google/gwt/user/client/ui/MenuBar.java index ec97492..be483f7 100644 --- a/user/src/com/google/gwt/user/client/ui/MenuBar.java +++ b/user/src/com/google/gwt/user/client/ui/MenuBar.java
@@ -227,6 +227,9 @@ * Removes all menu items from this menu bar. */ public void clearItems() { + // Deselect the current item + selectItem(null); + Element container = getItemContainerElement(); while (DOM.getChildCount(container) > 0) { DOM.removeChild(container, DOM.getChild(container, 0)); @@ -347,6 +350,11 @@ * @param item the item to be removed */ public void removeItem(MenuItem item) { + // Unselect if the item is currently selected + if (selectedItem == item) { + selectItem(null); + } + if (removeItemElement(item)) { setItemColSpan(item, 1); items.remove(item);
diff --git a/user/test/com/google/gwt/user/client/ui/MenuBarTest.java b/user/test/com/google/gwt/user/client/ui/MenuBarTest.java index 24925b8..fcfeff0 100644 --- a/user/test/com/google/gwt/user/client/ui/MenuBarTest.java +++ b/user/test/com/google/gwt/user/client/ui/MenuBarTest.java
@@ -134,4 +134,44 @@ }); delayTestFinish(250); } + + /** + * Test that the selected item points to the correct item. + */ + public void testSelectedItem() { + // Create a menu bar + MenuBar bar = new MenuBar(true); + + // Create a blank command + Command blankCommand = new Command() { + public void execute() { + } + }; + + // Add some items + MenuItem item0 = bar.addItem("item0", blankCommand); + MenuItem item1 = bar.addItem("item1", blankCommand); + MenuItem item2 = bar.addItem("item2", blankCommand); + MenuItem item3 = bar.addItem("item3", blankCommand); + MenuItem item4 = bar.addItem("item4", blankCommand); + + // Test setting the selected item + assertNull(bar.getSelectedItem()); + bar.selectItem(item1); + assertEquals(item1, bar.getSelectedItem()); + + // Test removing the selected item + bar.removeItem(item1); + assertNull(bar.getSelectedItem()); + + // Test removing an item that is not selected + bar.selectItem(item3); + assertEquals(item3, bar.getSelectedItem()); + bar.removeItem(item2); + assertEquals(item3, bar.getSelectedItem()); + + // Test clearing all items + bar.clearItems(); + assertNull(bar.getSelectedItem()); + } }