将对象绘制到画布(使用Eclipse中的Processing库)会返回意外错误

时间:2017-03-28 08:10:42

标签: java processing

我在Eclipse IDE中使用库Processing,我想绘制' Player'对象' p'使用p.show()方法到屏幕。所有其他Processing函数都可以工作,但是当运行this.show()函数时,它会返回如下所示的错误。如何解决这个问题?!

这个程序:

import processing.core.PApplet;

public class Game extends PApplet {
    public static void main(String[] args){
        PApplet.main("Game");
    }

    public Player p = new Player();
    public static int cW = 1000, cH = 600;
    public void settings(){
        size(cW,cH);

    }

    public void setup(){
        background(51);

    }

    public void draw(){
        p.show();
    }


}
//PLAYER.JAVA CLASS
import processing.core.PApplet;

public class Player extends PApplet{
    public int x,y,pSize = 30;
    public Player(){
        this.x = Game.cW/2;
        this.y = Game.cH/2; 

        }

    public void show(){
        noStroke();
        rect(this.x,this.y,this.pSize,this.pSize);
    }   

    }

返回错误:

java.lang.NullPointerException
  at processing.core.PApplet.noStroke(PApplet.java:13982)
  at Player.show(Player.java:12)
  at Game.draw(Game.java:21)
  at processing.core.PApplet.handleDraw(PApplet.java:2418)
  at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1540)
  at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)

1 个答案:

答案 0 :(得分:0)

你不应该有两个不同的类,它们都扩展PApplet。将PApplet的每个扩展名视为单独的草图。所以你真的只想要一个扩展PApplet的类。要访问其他类中的Processing函数,您必须传入对主草图的引用。它看起来像这样:

public class Player{

    private int x;
    private int y;
    private int pSize = 30;

    public Player(int x, int y, PApplet sketch){
        this.x = x;
        this.y = y;
        this.sketch = sketch; 
    }

    public void show(){
        sketch.noStroke();
        sketch.rect(x, y, pSize, pSize);
    }   
}

然后在您的主草图课程中,您使用this关键字传递对Player课程的自我引用:

public class Game extends PApplet {

    private Player p;

    private int cW = 1000;
    private int cH = 600;

    public void settings(){
        size(cW,cH);
        p = new Player(cW/2, cH/2, this);
    }

    //rest of your code