Java添加mouseListener并在其中使用局部变量
我想做的是在我添加的MouseStener中使用局部变量(就在那个地方)。这似乎是不可能的,所以我想问一下,对于我正在尝试做的事情,是否有其他的方法 所以基本上,问题是:我不能在我动态添加的mouseListener中使用局部变量(在我的例子中,它包含用户点击的产品的信息) 这是它的代码:Java添加mouseListener并在其中使用局部变量,java,swing,variables,instance-variables,mouselistener,Java,Swing,Variables,Instance Variables,Mouselistener,我想做的是在我添加的MouseStener中使用局部变量(就在那个地方)。这似乎是不可能的,所以我想问一下,对于我正在尝试做的事情,是否有其他的方法 所以基本上,问题是:我不能在我动态添加的mouseListener中使用局部变量(在我的例子中,它包含用户点击的产品的信息) 这是它的代码: public void mouseClicked(MouseEvent e) { //when user clicks on a label of a product //then add it t
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 ######################
}
public void mouseClicked(MouseEvent e){
//当用户单击产品标签时
//然后将其添加到cart_产品面板(标签)
//此外,还要在cart_产品的标签上添加鼠标侦听器
//这样,当鼠标右键单击标签时,它可以再次从购物车中删除
//a=店铺标识,索引[0]=类别标识,索引[1]=产品标识
JLabel=(JLabel)e.getSource();//单击的标签(产品)
int[]index=getProductIndex(label.getText());//获取所单击产品的索引
cart_products[a][index[0]][index[1]]=新的JLabel(“1x(“+当前+”)+产品价格[a][index[0]][index[1]]+“Euro-”+label.getText());
//在购物车内为单击的产品创建新标签
//“将其添加到购物车”
######################不工作启动
//在购物车内的新产品标签上添加鼠标侦听器
//要在产品标签上单击鼠标右键,请删除产品标签
cart_products[a][index[0]][index[1]].addMouseListener(新的MouseListener()){
公共无效mouseClicked(MouseEvent e){
if(旋转能力。isRightMouseButton(e)){
removeCartProduct(a,索引[0],索引[1]);//您可以使用声明为final
的局部变量:final int[]index=getProductIndex…
,对于a
也是如此