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。