2015-11-02 31 views
2

我正在尋找幾天來幫助我,但是我沒有發現任何問題,我真的不知道該怎麼做。在ArrayList中循環不起作用(Get()方法)

這是問題所在......我試圖讓我在這個ArrayList (urlPage)加入我的循環中的位置我的網址,但我得到這個編譯錯誤:我在一個封閉的範圍定義的局部變量必須爲final或有效的最終。我嘗試了很多東西,但沒有任何作用。

/* Create a loop starting with 0 and ending with 3 to add all the components into the panel */ 
     for (int i = 0; i < 3 ; i++) { 
      productIconLabel[i] = new JLabel(""); 
      productIconLabel[i].addMouseListener(new MouseAdapter() { 
       @Override 
       public void mousePressed(MouseEvent arg0) { 
        try { 
         Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlPage.get(i)); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 
       } 
      }); 

在循環中的代碼繼續(還有就是爲什麼這裏沒有結束支架的),但是這是我有問題的部分。 這是將url添加到ArrayList中的功能。

/* Function to receive part of information sent from the form page */ 
    public void radioButtonResult(int productIndexNumber, String productImageAddress, String productName, double productPrice, String url) { 
     productIconLabel[productIndexNumber].setIcon(new ImageIcon(productImageAddress)); 
     productNameLabel[productIndexNumber].setText(productName); 
     productPriceLabel[productIndexNumber].setText(Double.toString(productPrice) + " €"); 
     urlPage.add(productIndexNumber, url); 
    } 

唯一的問題是編譯錯誤。爲了做一些測試,我已經改變了我的0,1和2,它的工作。我感謝任何幫助。

+0

代碼中的哪一行會給出錯誤? – AbtPst

+0

是你的getRuntime()。exec的radioButtonResult函數的一部分嗎? – AbtPst

+0

這是一個:Runtime.getRuntime()。exec(「rundll32 url.dll,FileProtocolHandler」+ urlPage.get(i)) –

回答

2

你在新的MouseAdapter()中,所以它不知道變量i。不同的範圍。

使用最終變量。

for (int i = 0; i < 3 ; i++) { 
      final int currentIter = i; 
      productIconLabel[i] = new JLabel(""); 
      productIconLabel[i].addMouseListener(new MouseAdapter() { 
       @Override 
       public void mousePressed(MouseEvent arg0) { 
        try { 
         Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlPage.get(currentIter)); 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 

       } 
      }); 
+1

解決,謝謝:) –

+0

太棒了!很高興我們可以幫助 –

2

i需要是最終的才能在匿名內部類的方法內部訪問它。你可以做這樣的事情:

for (int i = 0; i < 3 ; i++) { 
     final int fi = i; 
     productIconLabel[i] = new JLabel(""); 
     productIconLabel[i].addMouseListener(new MouseAdapter() { 
      @Override 
      public void mousePressed(MouseEvent arg0) { 
       try { 
        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlPage.get(fi)); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 

      } 
     }); 
     ..... 
+0

解決,謝謝:) –

+0

@ElaineCristinaMeirelles偉大,祝你好運。 – Titus

1

你不能在匿名內部類中使用局部變量i。因爲這兩個範圍是不同的。