开发者

Java add mouseListener and use local variables inside

What I'm trying to do is use local variables inside of the mouseListener I add ( right on that place ). Which seems impossible, so I would like to ask if there's any alternative way for what I'm trying to do.

So basicly the problem is: I cannot use local variables ( which in my case contain info about the product clicked on by the user ) inside a mouseListener I add dynamicly.

This is the code it's about:

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 ###################### 

}

It's part of a big code so unfortunately I cannot post a full SSCCE with a compile- & execute-ready code. So I tried to just offer the code part that isn't working properly ( which I'm sure it only is this part marked with #s ). Anyway I hope one can give a solution for my problem.

Thanks in advance!

Best Regards, Skyfe.


You can use local variables declared as final: final int[] index = getProductIndex... and the same for a.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜