I am having somewhat of an issue getting an image from another class. I have never had this problem before. Can someone please point me in the right direction.
package main;
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Main extends JFrame {
public static Character character;
static GraphicsEnvironment graphicsEnvironment;
static GraphicsDevice graphicsDevice;
static DisplayMode displayMode;
private Image i;
public static void main(String[] args) {
displayMode = new DisplayMode(1280, 720, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();
Main m = new Main();
m.run();
}
public void run() {
setUndecorated(true);
setResizable(false);
graphicsDevice.setFullScreenWindow(this);
try {
graphicsDevice.setDisplayMode(displayMode);
} catch (Exception e) {
}
}
public void paint(Graphics g) {
g.setColor(Color.cyan);
g.fillRect(0, 0, displayMode.getWidth(), displayMode.getHeight());
i = character.getImage();
g.drawImage(i, 100, 100, this);
}
}
package main;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Character {
private Image i;
public Image getImage() {
i = new ImageIcon(this.getClass().getResource("/raw/images/player1.png")).getImage();
return i;
}
}
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main.Main.paint(Main.java:52)
It says that the error is i = character.getImage();
I have done this plenty of times when making applets, this if the first time I am trying a fullscreen game
Remember to think about what the compiler is telling you.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
A NullPointerException means a reference variable hasn't been initialized (or is == null
, for that matter). In your case, that means to debug it you'll have to check both i and character. If it was the image you were trying to return, the stacktrace would go one deeper.
Since you are initializing i, look back up at character. You never set character to anything, which means you can't use it in any declarations.
So, your solution is to do character = new Character();
in run()
or main(String[] args)
,
or you can set getImage()
to static, and say i = Character.getImage();
.