java添加mouseListener并在里面使用局部变量

标签 java swing variables instance-variables mouselistener

我想做的是在我添加的 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.

最佳答案

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

关于java添加mouseListener并在里面使用局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4146610/

相关文章:

java - 如何将点击事件添加到 javafx 中的 tableview 单元格

java - 在 appium 中使用触摸操作向下滚动移动应用程序时显示异常

java - JPQL,获取具有子列表的对象列表,避免n+1请求并仅选择特定字段

java - Swing 中的绘画不起作用

variables - 批处理脚本中变量中的转义字符

java - 将任务标记为延迟

java - 使用 Java Swing 和 AWT 获得完全相同的代码的不同输出

java - JTable 中的 JProgressBar 未更新

mysql - 在 bash 脚本中从 MySQL 数据库写入变量

javascript - 无法设置 null 的属性 'innerHTML' - 似乎没有办法修复它