Я работаю над двумерной игрой, и всякий раз, когда я импортирую изображения классов противника, это дает мне следующую ошибку при запуске игры. Всякий раз, когда изображения удаляются из игровой папки, игра проходит отлично. Любая помощь будет оценена.Ошибка NullPointerException при импорте изображений
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at OurGame.Board.checkCollisions(Board.java:69)
at OurGame.Board.actionPerformed(Board.java:40)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Все игровые классы, которые я поставил вместе, чтобы они могли общаться друг с другом. Здесь ниже я вставить все мои игровые классы:
//Frame.java//
package OurGame;
import javax.swing.*;//imports the graphics of the JFrame, always comes after the package or a error will be received
public class Frame {
public static void main(String[] args)
{
JFrame frame = new JFrame("A Game Designed For Kejsi!");
frame.add(new Board());//goes to the constructor of board
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//when the frame is closed, it just exits it
frame.setSize(1024,768);//sets the size with the dimensions of the background picture
frame.setVisible(true);//makes it visible
}
}
//Board.java//
package OurGame;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
public class Board extends JPanel implements ActionListener, Runnable{//you need to extend the panel, cause this class is a panel
Girl p;//creates a instance of the girl
Image img;//this image will contain the background image
Timer time;//this is used because the frame is going to be updated, because I will move the character
int v =300;
Thread animator;
Enemy en;
Enemy en2;
boolean lost = false;//determines wether or not the game is lost
static Font font = new Font("SanSerif", Font.BOLD,24);//creates a new font used for writing inside the graphics/paint method
public Board()
{
p = new Girl();
addKeyListener(new AL());//listens all the time for any keys pressed or released
setFocusable(true);// it allows or not a component to receive focus from mouse or keyboard.
ImageIcon i = new ImageIcon("C:/Users/Marjo/Desktop/GameI/test.png");
img = i.getImage();//img stores background image
time = new Timer(2, this);//updates the screen every 5 milliseconds
time.start();//this will run a method for the action perform therefore we need to implement ActionListener
en = new Enemy(p.x+1000,500, "C:/Users/Marjo/Desktop/GameI/enemy.png");
en2 = new Enemy(p.x+1200,400,"C:/Users/Marjo/Desktop/GameI/fish.png");
}
public void actionPerformed(ActionEvent e)
{
checkCollisions();//checks for collisions every 5 milliseconds
ArrayList bullets = Girl.getBullets();//adds any new bullets every 5 milliseconds
for(int w = 0; w< bullets.size();w++)
{
Bullet m = (Bullet) bullets.get(w);
if(m.getVisible()==true)//if the bullet is visible it will move it
{
m.moveRight();
}
else
bullets.remove(w);//if the bullet is not visible it will remove it
}
p.move();//makes the character move every 5 millisecond
repaint();//repaints every 5 milliseconds
if(p.x>400)//shows where the enemy spawns
{
en.move(p.getDx());
}
if(p.x>500)
{
en2.move(p.getDx());
}
}
public void checkCollisions()//checks for collisions
{
Rectangle r1 = en.getBounds();
Rectangle r2 = en2.getBounds();
ArrayList bullets = Girl.getBullets();//goes through all the bullets and checks for collisions with the enemies
for(int w = 0; w< bullets.size();w++)
{
Bullet m = (Bullet) bullets.get(w);
Rectangle m1 = m.getBounds();
if(r1.intersects(m1) && en.isAlive())//if the bullet touches the enemy
{
en.isAlive=false;
m.visible=false;
}
else
if(r2.intersects(m1)&& en2.isAlive())
{
en2.isAlive=false;
m.visible=false;
}
}
Rectangle d = p.getBounds();
if(d.intersects(r1)&&en.isAlive==true)
{
lost = true;
}
else
if(d.intersects(r2)&&en2.isAlive==true)
{
lost = true;
}
else
lost = false;
}
boolean k = false;
public void paint(Graphics g)
{
if(lost)//determines what to do when the game is lost
{
System.out.println("YOU LOST THE GAME. Marjo's minions defeated you!");
System.exit(0);
}
if(p.dy==2 && k == false)//when jumping we want animation(thread to start)
{
k = true;
animator = new Thread(this);
animator.start();
}
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
if((p.getX()-170)%2040 == 0)//if it is at 166,1166,2166 etc. checks every 2000 pixels
p.nx = 0;
if((p.getX()-1186)%2040 == 0)//like above...
p.nx2 = 0;
g2d.drawImage(img, 1000-p.nx2, 0, null);//without this the game would be blank, draws the background
if(p.getX()>166)//starts a new background after the first one finishes
{
g2d.drawImage(img, 1000-p.nx, 0, null);//without this the game would be blank, draws the background
}
g2d.drawImage(p.getImage(), p.left, v, null);//draws character and keeps its position updated thanks to getImage(),getX() and getY()
ArrayList bullets = Girl.getBullets();
for(int w = 0; w< bullets.size();w++)
{
Bullet m = (Bullet) bullets.get(w);
g2d.drawImage(m.getImage(), m.getX(), m.getY(), null);
}
g2d.setFont(font);
g2d.setColor(Color.BLUE);
g2d.drawString("Ammo left: "+ p.ammo,400,20);//draws the text ammo left at 500 right and 20 down pixels (position)
//prints the enemy only after a certain point in the game
if(p.x>400)
{
if(en.isAlive == true)
{
g2d.drawImage(en.getImage(),en.getX(),en.getY(),null);
}
}
if(p.x>500)
{
if(en2.isAlive == true)
{
g2d.drawImage(en2.getImage(),en2.getX(),en2.getY(),null);
}
}
}
private class AL extends KeyAdapter{//just determines which key was pressed
public void keyReleased(KeyEvent e)//tells us which key was released
{
p.keyReleased(e);
}
public void keyPressed(KeyEvent e)//which key was pressed
{
p.keyPressed(e);
}
}
//this is used for threads (jumping) and is a result of implementing runnable
public void run() {
long beforeTime,timeDiff,sleep;
//weird method to time jumping animation, always use this
beforeTime = System.currentTimeMillis();
while(done == false)//this will keep looping as long as the jump is not done
{
cycle();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = 10/*the speed of jumping, maybe not, for speed look below at the v++,v-- crap*/ - timeDiff;
if(sleep <= 0)
sleep = 2;
try{
Thread.sleep(sleep);
} catch(Exception e)
{}
beforeTime = System.currentTimeMillis();
}
k = false;
h = false;
done = false;
}
//changes the y value of the character
boolean h = false;//when at the peak of jump
boolean done = false;//when done jumping
public void cycle()
{
if(h == false)//it will continue jumping up as long as it is not at max height
{
v-=5;
p.bullh = v;//the bullh value makes sure that bullets that are shot get shot at the same height with the character
//which is v, therefore the variable bullh is the height of the shot bullets
}
if(v==100)//h becomes true once at max height
{
h = true;
p.bullh = v;
}
if(h == true && v<=460)//once at max height it will start descending making sure it doesn't go under the ground
{
v+=5;
p.bullh = v;
}
if(v == 300)//the jump is finished
{
done = true;
p.bullh = v;
}
}
}
//Girl.java//
package OurGame;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Girl {
int x,dx,y,nx2,nx,left,dy;//the x coordinate and the change in the x coordinate
Image still;
ImageIcon i = new ImageIcon("C:/Users/Marjo/Desktop/GameI/still.png");
//creates the girl, but moving to the left
ImageIcon l = new ImageIcon("C:/Users/Marjo/Desktop/GameI/stillLeft.png");
static ArrayList bullets;//stores the bullets
int ammo = 30;
int bullh = 450; //I created this variable to make sure bullets get shot at same height
public Girl()
{
still = i.getImage();
left = 150;
x = 150;
y = 300;
nx2 = 1000;
nx = 0;
bullets = new ArrayList();
}
public static ArrayList getBullets()
{
return bullets;
}
public void fire()//if more than 0 ammo creates a new bullet and adds it to an array list to be displayed on screen
{
if(ammo>0)
{
ammo--;
Bullet z = new Bullet((left + 100),bullh + 100);
bullets.add(z);
}
}
public void move()
{
if(dx!=-2)//makes it move only to the right, but is fixed below
{
if(left + dx<=350)
left = left + dx;//this moves the actual character to the right since left controls the characters physical position without moving
//screen
else
{
x = x + dx;
nx2 = nx2 + dx;
nx = nx + dx;
}
}
else
{
if(left+dx > 0)//will move left if not out of screen
{
left = left + dx;
}
}
}
public Rectangle getBounds()//assumes the girl is a rectangle and gets its bounds
{
return new Rectangle(left,y,75,240);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public int getDx()
{
return dx;
}
public Image getImage()
{
return still;
}
public void keyPressed(KeyEvent e)//will move the character if a key is pressed
{
int key = e.getKeyCode();//the integer code for an actual key in the keyboard
if(key == KeyEvent.VK_LEFT)
{
dx = -2;
still = l.getImage();
}
if(key == KeyEvent.VK_RIGHT)
{
dx = 2;
still = i.getImage();
}
if(key == KeyEvent.VK_UP)
{
dy = 2;
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();//the integer code for an actual key in the keyboard
if(key == KeyEvent.VK_LEFT)
dx = 0;//the character will stop if the keys are released
if(key == KeyEvent.VK_RIGHT)
dx = 0;
if(key == KeyEvent.VK_UP)
dy = 0;
if(key == KeyEvent.VK_SPACE)
fire();
}
}
//Bullet.java//
package OurGame;
import java.awt.*;
import javax.swing.ImageIcon;
public class Bullet {
int x,y;
Image img;
boolean visible;//the bullet will be visible unless it hits something or goes out of the screen
public Bullet(int startX, int startY)
{
x = startX;
y = startY;
ImageIcon newBullet = new ImageIcon("C:/Users/Marjo/Desktop/GameI/bullet.png");//the bullet picture stored in the hard drive
img = newBullet.getImage();
visible = true;//the bullet is initially visible
}
public void moveRight()
{
x = x + 6;//the bullet will move 6 pixels per millisecond
if(x>1024)//if the bullet is outside the board it is no longer visible
{
visible = false;
}
}
public Rectangle getBounds()//assumes the bullet is a rectangle and gets its bounds
{
return new Rectangle(x,y,54,16);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public boolean getVisible()
{
return visible;
}
public Image getImage()
{
return img;
}
}
//Enemy.java//
package OurGame;
импорт java.awt.Image; import java.awt.Rectangle;
импорт javax.swing.ImageIcon;
класс Enemy общественного {
Image img;
int x,y;
boolean isAlive = true;
public Enemy(int startX, int startY, String location)
{
x = startX;
y = startY;
ImageIcon l = new ImageIcon(location);//the reason why we are doing this is because we want to use more than one appearance of an enemy
img = l.getImage();
}
public Rectangle getBounds()//assumes is a rectangle and gets its bounds
{
return new Rectangle(x,y,175,175);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public boolean isAlive()
{
return isAlive;
}
public Image getImage()
{
return img;
}
public void move(int dx)
{
if(dx!=-2)//makes sure the enemies don't go further away
x = x-dx;//when the player moves the enemy seems to be moving from right to left
}
}
который является строкой 69 в 'Board.java'? – jlordo
Существует одна причина для 'NullPointerException'. У вас есть переменная, которая содержит «null» в качестве эталонного значения, и вы пытались ее использовать. Поместите его в отладчик и выясните, почему это не то, что вы ожидаете. –
public void checkCollisions() // проверка коллизий \t { Линия 69 \t ====> \t Rectangle r1 = en.getBounds(); – user2031169