簡體   English   中英

Java數組索引超出范圍異常:-1

[英]Java Array Index Out Of Bounds Exception: -1

好吧,我有一個問題,我不知道怎么了。 所以我有jList和List。 我需要一個函數,當我單擊項目(在jList中的任何項目中)時,它會在標簽圖標(我正在處理圖像)中發生變化。 它以某種方式工作,將我的標簽圖標更改為我從jList中選擇的圖像,但是它引發了異常,程序崩潰了,通常前2個項目沒有引起錯誤,第三個項目導致了它。 當它崩潰並拋出紅色文本后,我仍然可以更改圖標。

這是我獲取圖像並將其添加到列表(向其添加路徑)的功能

private static void getImages(String src) throws IOException {
    //Exctract the name of the image from the src attribute
    int indexname = src.lastIndexOf("/");

    if (indexname == src.length()) {
        src = src.substring(1, indexname);
    }

    indexname = src.lastIndexOf("/");
    String name = src.substring(indexname, src.length());

    //Open a URL Stream
    URL url = new URL(src);
    InputStream in = url.openStream();

    GPath=fPath+name;
    OutputStream out = new BufferedOutputStream(new FileOutputStream( GPath));
    //Im adding to the list string (link to image) here
    imagesListN.add(GPath);

    System.out.println("list size: "+imagesListN.size());


    for (int b; (b = in.read()) != -1;) {

        out.write(b);
    }

    out.close();
    in.close();

}

它通常添加它們。 是的,我正在下載它們,這就是為什么我要在下載它們后查看它們。

這是我單擊jList函數的地方。

     list.addListSelectionListener(new ListSelectionListener() {

        private int a;

        @Override
        public void valueChanged(ListSelectionEvent arg0) {
            if (!arg0.getValueIsAdjusting()) {
                String h;
                int k;
                k = list.getSelectedIndex();
                System.out.println("List id: "+k);
                a = Main.imagesListN.indexOf(k);
                System.out.println("imagesListN id: "+a);

                h = Main.imagesListN.get(k);
                System.out.println("h : "+h);
                ImageIcon img = new ImageIcon(h);

                imageReview.setIcon(img);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    });

這是jList(名稱列表)。 例外在

一個= Main.imagesListN.indexOf(k);

它給我-1,但是h = Main.imagesListN.get(k); 給我所需的鏈接,並將其提供給ImageIcon img = new ImageIcon(h); 然后是imageReview.setIcon(img); 當我單擊所需項目時,標簽圖標每次都會更改。 也許不是= Main.imagesListN.indexOf(k); 我正在看的東西,但是某些東西讓我為-1。 順便說一句,我正在執行線程中的所有內容。

`public class Crawler extends Thread {

Main main = new Main();

public void run(){
        try {
                main.download();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}`

這里沒什么好看的。 每個函數都在自己的類中,getImages()在main中,listListener在Langas類中(所有按鈕,標簽等均未創建的Class)以及Thread和Thread。 一切下載完成后,它也可以正常工作,沒有例外。 在下載過程中出現錯誤

indexOf api接受Object作為參數,而get接受Object以及原始類型。 因此,當您使用基本類型element調用get時,它將通過您可能已找到的索引來查找element。

但是當執行indexOf時,您正在列表中搜索對象,因此得到-1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM