【发布时间】:2009-10-04 23:09:13
【问题描述】:
我正在阅读 GWT 的教程,被这段代码弄糊涂了。
private void addStock() {
final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
// Stock code must be between 1 and 10 chars that are numbers, letters,
// or dots.
if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + symbol + "' is not a valid symbol.");
newSymbolTextBox.selectAll();
return;
}
newSymbolTextBox.setText("");
// Don't add the stock if it's already in the table.
if (stocks.contains(symbol))
return;
// Add the stock to the table.
int row = stocksFlexTable.getRowCount();
stocks.add(symbol);
stocksFlexTable.setText(row, 0, symbol);
stocksFlexTable.setWidget(row, 2, new Label());
stocksFlexTable.getCellFormatter().addStyleName(row, 1,
"watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(row, 2,
"watchListNumericColumn");
stocksFlexTable.getCellFormatter().addStyleName(row, 3,
"watchListRemoveColumn");
// Add a button to remove this stock from the table.
Button removeStockButton = new Button("x");
removeStockButton.addStyleDependentName("remove");
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);
// Get the stock price.
refreshWatchList();
}
问题部分是匿名内部类将事件处理添加到removeStockButton。该类的 onClick 方法接受一个事件,然后使用变量 symbol 从 ArrayList stocks 中检索要删除的行的索引。
当用户实际调用 onClick()(即单击删除按钮)时,symbol 如何仍然在范围内?如果您怀疑代码的正确性,它来自 Google 工程师,因此是正确的(另外,它有效,我已经使用过)。
这是一些 JavaScript 技巧还是我需要 Java 参考课程?
【问题讨论】:
-
与javascript无关...
标签: java javascript gwt