2010-11-10 146 views
2

内部的局部变量我想要做的是使用我添加的mouseListener(在那个地方)的局部变量。这似乎是不可能的,所以我想问一下,如果有什么替代方式,我正在尝试做什么。Java添加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。

回答

2

您可以使用声明为final的局部变量:final int[] index = getProductIndex...a相同。

相关问题