2

私がやろうとしているのは、追加した 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 でマークされたこの部分だけだと確信しています)。とにかく、私の問題を解決できることを願っています。

前もって感謝します!

よろしく、スカイフ。

4

1 に答える 1

2

として宣言されたローカル変数を使用できfinalます。final int[] index = getProductIndex...a

于 2010-11-10T16:41:20.807 に答える