The following example is taken from GWT tutorial (http://code.google.com/webtoolkit/doc/latest/tutorial/codeclient.html):

private void addStock() {
  	final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
	newSymbolTextBox.setFocus(true);

	if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
		Window.alert("'" + symbol + "' is not a valid symbol.");
		newSymbolTextBox.selectAll();
		return;
	}

	if (stocks.contains(symbol)) {
		newSymbolTextBox.selectAll();
		return;
	}

	int row = stocksFlexTable.getRowCount();
	stocks.add(symbol);
	stocksFlexTable.setText(row, 0, symbol);

	Button removeStockButton = new Button("x");
	removeStockButton.addClickHandler(new ClickHandler() {
		public void onClick(ClickEvent event) {
			int removedIndex = stocks.indexOf(symbol);
			stocks.remove(removedIndex);
			stocksFlexTable.removeRow(removedIndex+1);
		}
	});
	stocksFlexTable.setWidget(row, 3, removeStockButton);

	newSymbolTextBox.setText("");
	refreshWatchList();
  }

I have hard time understanding this: the clickhandler of removeStockButton is getting the index of the symbol and then removes from arrayList. How is the handler know dynamically about symbol? Because symbol is a variable define in the addstock method. During compile time or when the addStock() method is entered, symbol is known. But during run time when a button is clicked and the clickhandler code is entered now how does it know symbol it independent of addStock(). It is behaving like ruby generator. How does it work? Where is the magic here?

Thanks.

Recommended Answers

All 2 Replies

The instance of the anonymous inner class exists only in the context of the runtime stack of the method, is a method local variable and as such has access to other method local variables of that same method instance.

The "final" keyword is essential here. The compiler knows that the value assigned to the variable can not be changed, so its value can be used in the inner class even after the method has terminated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.