2013-06-16 2 views
1

배열을 arrayList로 변경 중입니다. 여러 번의 시도에서 오류 "NullPointerException"이 발생하면 아래 코드와 같이 코드가 단순화되어 mousePressed 때 사각형이 만들어집니다. 하지만 여전히 같은 오류가 있습니다. 문제가 무엇입니까?ArrayList 오류 "NullPointerException"

ArrayList textlines; 

int xpos=20; 
int ypos=20; 

void setup() { 
    size(1200, 768); 
    ArrayList textlines = new ArrayList(); 
    //(Line)textlines.get(0) =textlines.add(new Line(xpos, ypos)); 
} 

void draw() { 
} 


void mousePressed() { 
    textlines.add(new Line(xpos, ypos)); 
    for (int i=0; i<textlines.size(); i++) { 

    Line p=(Line)textlines.get(i); 
    p.display(); 
    } 
} 


class Line { 

    int x; 
    int y; 

    Line(int xpo, int ypo) { 
    x =xpo; 
    y =ypo; 
    } 

    void display() { 
    fill(50, 50, 50); 
    rect(x, y, 5, 5); 
    } 
} 
+3

항상 예외에 대한 질문을 게시 할 때, 선이 예외를 throw 스택 트레이스와 쇼를 게시 할 수 있습니다. –

+1

'setup()'이 언제 호출 될까요? – haraldK

+2

화가 프로그래머가 stacktrace에 관해 묻는 많은 미친 댓글을 얻을 수 있습니다. 그들이 오기 전에 그것을하십시오. – Maroun

답변

5

당신은 가능성이 변수 여기 textlines을 미행하고 있습니다 : 당신은 이후

ArrayList textlines = new ArrayList(); 

setup() 방법을 다시 선언. 그러지 마. 클래스에서 한 번 선언하십시오.

특히, 의견을 확인하십시오

ArrayList textlines; 

void setup() { 
    // ... 

    // *** this does not initialize the textlines class field 
    // *** but instead initializes only a variable local to this method. 
    ArrayList textlines = new ArrayList(); 

} 

이 문제를 해결하려면 :

ArrayList textlines; 

void setup() { 
    // ... 

    // *** now it does 
    textlines = new ArrayList(); 

}