2

我想要做的是在我添加的 mouseListener 中使用局部变量(就在那个地方)。这似乎是不可能的,所以我想问一下我正在尝试做的事情是否有其他方法。

所以基本上问题是:我不能在我动态添加的mouseListener中使用局部变量(在我的例子中包含用户点击的产品的信息)。

这是它的代码:

public void mouseClicked(MouseEvent e) {

  //when user clicks on a label of a product
  //then add it to the cart_products panel (label)
  //also add a mouseListener to the label for the cart_products
  //so that it can be removed from the cart again when right-mouse clicked on the label

  //a = shop_id, index[0] = category_id, index[1] = product_id

JLabel label = (JLabel)e.getSource(); //the label clicked on (product)

int[] index = getProductIndex(label.getText()); //gets the indexes of the product clicked on

cart_products[a][index[0]][index[1]] = new JLabel("1x ("+current+") "+product_prices[a][index[0]][index[1]]+" Euro - "+label.getText());

//create a new label inside the shopping cart for the product clicked on
//to 'add it to the shopping cart'

###################### NOT WORKING START ###################### 
//add a mouseListener to the new product label inside the shopping cart
//to make a right-mouse click on the product label, remove the product label
cart_products[a][index[0]][index[1]].addMouseListener(new MouseListener() {

  public void mouseClicked(MouseEvent e) {
    if(SwingUtilities.isRightMouseButton(e)){
      removeCartProduct(a, index[0], index[1]); //<!--- cannot use these local variables
    }
  }

}
###################### NOT WORKING  END ###################### 

}

它是大代码的一部分,所以很遗憾,我无法发布带有编译和执行就绪代码的完整 SSCCE。所以我试图只提供无法正常工作的代码部分(我确信它只是用 #s 标记的部分)。无论如何,我希望有人可以为我的问题提供解决方案。

提前致谢!

最好的问候, Skyfe。

4

1 回答 1

2

您可以使用声明为final:final int[] index = getProductIndex...的局部变量,对于a.

于 2010-11-10T16:41:20.807 回答