NPE (New to Processing)
in
Programming Questions
•
11 months ago
Hello, I'm trying to write a template program for buttons and menus, but I run into a NullPointerException when I try and construct the button class, in line 17.
I am new to Processing, and I have never used Classes before.
Here is my code:
- int menu = 1;
- Button[] mainmenu;
- //Button[] optionsmenu;
- //Button[] levels;
- //Button[] game;
- void drawMenu(Button[] m){
- for (int i = 0; i < m.length; i++){
- m[i].draw();
- }
- }
- void setup(){
- size(800, 640);
- //pos x, pos y, size x, size y, to menu id, from menu id, image name
- mainmenu[0] = new Button(width/2, height/3, 160, 40, 3, 1, "PlayButton.jpg");
- mainmenu[1] = new Button(width/2, height/2, 160, 40, 2, 1, "OptionsButton.jpg");
- mainmenu[2] = new Button(width/2, 2*height/3, 160, 40, 999, 1, "ExitButton.jpg");
- }
- void draw(){
- background(0);
- if (menu == 1){
- drawMenu(mainmenu);
- }
- }
- class Button {
- int px;
- int py;
- int sx;
- int sy;
- int ToMenu;
- int InMenu;
- String sprite;
- PImage img;
- //Constructor!
- Button(int tpx, int tpy, int tsx, int tsy, int tToMenu, int tInMenu, String sprite){
- img = loadImage(sprite);
- px = tpx;
- py = tpy;
- sx = tsx;
- sy = tsy;
- ToMenu = tToMenu;
- InMenu = tInMenu;
- }
- void draw(){
- image(img, px-(sx/2), py-(sy/2));
- }
- void mouseover(){
- if (mouseX > px-(sx/2) && mouseX < px+(sx/2)){
- if (mouseY > py-(sy/2) && mouseY < py+(sy/2)){
- menu = ToMenu;
- }
- }
- }
- //End Class
- }
- void mousePressed(){
- if (menu==1){
- for (int i = 0; i < 3; i++){
- mainmenu[i].mouseover();
- }
- }
- }
Here is the error stack:
- Exception in thread "Animation Thread" java.lang.NullPointerException
- at Buttons.setup(Buttons.java:35)
- at processing.core.PApplet.handleDraw(PApplet.java:2103)
- at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:190)
- at processing.core.PApplet.run(PApplet.java:2006)
- at java.lang.Thread.run(Thread.java:662)
Thank you!
1