Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

java - Eclipse suggests Null Pointer exception, though I believe I initialized my object

As the title says I have NPE error. It happens on line:

while (getWidth() > bowl.getX()+10) {

If I remove it, it shows it happens on next line:

bowl.move(10.0, 0);

I concluded that eclipse does not see my "bowl" initialized. Why? Doesn't "new GOval" deal with that? I've seen in one of the threads here that a solution was to split declaration and initialization to different lines, but I think it is unlikely to be a primary solution (besides, it didn't help in my case) Any suggestions on this code?

This code is supposed to create a circle, put it in the left-upper corner of the screen, and move the circle after mouse-button is clicked. The circle is drawn successfully, but the NPE message shows up after the click.

import acm.program.*;
import acm.graphics.*;
import java.awt.event.*;

public class animation extends GraphicsProgram {

public void init() {
    GOval bowl = new GOval(10,10);
    add(bowl);
    addMouseListeners();
}


public void mouseClicked(MouseEvent e) {
        while (getWidth() > bowl.getX()+10) {
        bowl.move(10.0, 0);
        pause(50);
    }
}

private GOval bowl; 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The line:

GOval bowl = new GOval(10,10);

is declaring a new GOval and hiding the global GOval defined at the bottom.

That line should just be:

bowl = new GOval(10,10);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...