'Error "You may be mixing active and static modes" in Processing

I am trying to create a simple spaceship game, where there are meteorites falling from the top of the screen. I haven't come far but I got this error that says that my first line is mixing active and static mode but when i put it in the void loop it doesn't run.

Disclaimer for my bad code: i am just starting with Processing and programming in general.

PImage bg = loadImage("data/space.jpg"); //Where the error occurred
PImage spaceship = loadImage("data/spaceship.png");
PImage shot = loadImage("data/shot.png");

int movex = 300;
int movey = 700;
int shotx = 10;
int shoty = 10;

left  = false;
right = false;
down  = false;
up    = false;
space = false;

void setup () {
  size(600,800);
  background(bg);
  
  imageMode(CENTER);
  print("hello world");
  
}

void draw () {
   background(bg);
   
   
   image (spaceship,movex,movey);
}

void keyPressed () {
  if (key == CODED){
  }
  
  if (keyCode == LEFT){
    left = true;
  }
  
  if (keyCode == RIGHT){
    right = true;
  }
  
  if (keyCode == DOWN){
    down = true;
  }
  
  if (keyCode == UP){
    up = true;
  }
  
  if (key == ' '){
     space = true;
  }
}

void keyReleased () {
  if (keyCode == LEFT){
    left = false;
  }
  
  if (keyCode == RIGHT){
    right = false;
  }
  
  if (keyCode == DOWN){
    down = false;
  }
  
  if (keyCode == UP){
    up = false;
  }
  
  if (key == ' '){
     space = false;
  }
}


Solution 1:[1]

Try making the following changes:

boolean left  = false;
boolean right = false;
boolean down  = false;
boolean up    = false;
boolean space = false;

PImage spaceship;
PImage shot;
PImage bg;

void setup () {
  size(600,800);
  background(0);  
  imageMode(CENTER);
  print("hello world\n");
  bg = loadImage("space.jpg");
  spaceship = loadImage("spaceship.png");
  shot = loadImage("shot.png");  
}

void draw () {
   background(0);   
   image(spaceship,movex,movey);
}

  1. left, right, down, etc are booleans.
  2. background needs to be a rgb color or an integer (PImage won't work)
  3. move loadImage() calls to setup(). Don't need 'data/xxxx'; Processing knows to find the images in the 'data' folder.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1