i was making a program, game in specific, so i started with basic things, but when i try to test it it drops out weird errors which doesn't appear in code, so i suppose my code is fine, but i don't know what could be causing this. :(
This is the error:
Exception in thread "main" java.lang.NullPointerException
at java.awt.image.BufferedImage.<init>(Unknown Source)
at ca.hawk.game.Game.<init>(Game.java:33)
at ca.hawk.game.Game.main(Game.java:126)
And here's the code (package):
package ca.hawk.game;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.IndexColorModel;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 3;
public static final String NAME = "Game";
private static final int BufferedImage = 0;
private static final IndexColorModel TYPE_INT_RGB = null;
private JFrame frame;
public boolean running = false;
public int tickCount = 0;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage, TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
public Game(){
setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public synchronized void start() {
running = true;
new Thread(this).start();
}
private synchronized void stop(){
running = false;
}
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D/60D;
int ticks = 0;
int frames = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
while (running){
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
boolean shouldRender = true;
while (delta >= 1){
ticks++;
tick();
delta -= 1;
shouldRender = true;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (shouldRender){
frames++;
render();
}
if (System.currentTimeMillis() - lastTimer > 1000){
lastTimer += 1000;
System.out.println(frames +", "+ ticks);
frames = 0;
ticks = 0;
}
}
}
public void tick(){
tickCount++;
}
public void render(){
BufferStrategy bs = getBufferStrategy();
if (bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public static void main(String[] args){
new Game().start();
}
}
change :
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage, TYPE_INT_RGB);
to:
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage, BufferedImage.TYPE_INT_ARGB);
you set a varialbe TYPE_INT_RGB that is null, so when you make a buffered image it throws null pointer exception.
TYPE_INT_RGB is a public static final variable on BufferedImage. Public means you can access it in your object, static means its a class variable not an object variable and final means its ts always the same value e.g if its 10 it will always be 10.
with BufferedImage.TYPE_INT_RGB you can access it.
Related
When I run my game the JFrame is just white. Can someone explain?
I have no idea why this is happening and I'm having a really hard time finding out what could be the issue. I hope one of you can explain/know the answer. I look forward to hearing your answer and I would love to continue coding but I'm stuck atm, - Artycal.
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class Game extends Canvas implements Runnable {
static GraphicsDevice device = GraphicsEnvironment
.getLocalGraphicsEnvironment().getScreenDevices()[0];
private static JFrame frame;
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private BufferedImage image = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_ARGB);
private BufferedImage spriteSheet = null;
private static double width = screenSize.getWidth();
private static double height = screenSize.getHeight();
private boolean running;
private Thread thread;
private BufferedImage player;
public void init() {
BufferedImageLoader loader = new BufferedImageLoader();
try{
spriteSheet = loader.loadImage("/sprite_sheet.png");
}catch (IOException e){
e.printStackTrace();
}
SpriteSheet ss = new SpriteSheet(spriteSheet);
player = ss.grabImage(1, 1, 32, 32);
}
public void run() {
init();
long lastTime = System.nanoTime();
final double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int updates = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while (running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if (delta >= 1){
tick();
updates++;
delta--;
}
render();
frames++;
if (System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println(updates + " Ticks, Fps " + frames);
updates = 0;
frames = 0;
}
}
stop();
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(new Color(81, 218, 221));
g.drawRect(0, 0, getWidth(), getHeight());
g.setColor(new Color(81, 218, 221));
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
g.setColor(new Color(255, 174, 80));
g.drawImage(player, 100, 100, this);
g.dispose();
bs.show();
}
private void tick() {
}
public static void main(String[] args){
Game game = new Game();
frame = new JFrame("Game");
frame.setMaximumSize(new Dimension((int)width, (int)height));
frame.setMinimumSize(new Dimension((int)width, (int)height));
frame.setPreferredSize(new Dimension((int)width, (int)height));
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(game);
frame.pack();
frame.setVisible(true);
//device.setFullScreenWindow(frame);
game.start();
}
private synchronized void start() {
if (running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop() {
if (!running)
return;
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(1);
}
}
some things to note:
INT_ARGB for BufferedImage has a default alpha of 0 (completely clear) so unless you change the alpha value of the pixels you wont see anything.
drawRect draws only the outline of the rectangle. use fillRect to draw the entire rectangle.
as far as I know, drawing BufferedImages does not use the current color of the Graphics object as they are mainly defined as a rectangle made of different colored pixels. try drawing to the Images own Graphics object if you want to change its color.
you are exactly overlapping two drawings (the image and the rect) so you will only ever see one.
I hope I have finally been of some help.
Hello I am kind of new to java. I am working on a game. when the game starts a loading screen appears and the fades away that's it so far. My question is simple. Is there a way to change the image size to fit the size of the computer screen. I want it to fit all types of screen sizes and be a larger scale of the original image. Here is my Main class so far(there are other classes like player and title and play but they are irrelevant to the question:
package Main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Comp extends Canvas implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
public boolean run = true;
public Image screen, img;
public static double dir = 5;
public static int pixelSize = 1;
public static Dimension size = new Dimension(680, 500);
public static Dimension pixel = new Dimension(size.width / pixelSize,
size.height / pixelSize);
public static int mx;
public static manager m;
public static int my;
public static int fps;
public static boolean mr;
public static boolean ml;
JFrame frame = new JFrame();
public Thread t;
public boolean splashscreen = true;
public int time = 0;
public int timer = 140;
public int btime = 0;
public int btimer = 1;
private int FPS = 5;
private long targetTime = 1000 / FPS;
public Comp() {
setPreferredSize(size);
setFocusable(true);
addKeyListener(this);
addKeyListener(new listen());
addMouseListener(new listen());
addMouseMotionListener(new listen());
addMouseWheelListener(new listen());
m = new manager();
requestFocus();
// h = new InputHandler(this);
}
public void start() {
run = true;
frame.add(this);
frame.pack();
frame.requestFocus();
frame.setTitle("In The Maze");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setIconImage(new ImageIcon("res/traps/beartrap1.png").getImage());
t = new Thread(this);
t.start();
}
public void stop() {
run = false;
}
public static void main(String[] args) {
Comp c = new Comp();
c.start();
}
public void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(2);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, 1000, 1000);
if (!splashscreen) {
m.render(g);
}
if(splashscreen){
ImageIcon i62 = new ImageIcon("res/splashscreen.png");
img = i62.getImage();
g.drawImage(img,(int)0 ,(int)0,Comp.size.width+10,Comp.size.height + 10,null);
time++;
}
g.dispose();
bs.show();
}
public void tick() {
if(time >= timer){
time = 0;
splashscreen = false;
}
if(!splashscreen){
m.tick();
}
Keys.update();
Esentials.tick();
}
public void run() {
screen = createVolatileImage(pixel.width, pixel.height);
long start;
long elapsed;
long wait;
long currentTime = System.currentTimeMillis();
while (run) {
start = System.nanoTime();
fps++;
if(System.currentTimeMillis() - currentTime >= 1000){
// System.out.println("fps:" + fps);
currentTime = System.currentTimeMillis();
fps = 0;
}
tick();
render();
elapsed = System.nanoTime() -start;
wait = targetTime = elapsed / 1000000;
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void keyTyped(KeyEvent i) {
}
public void keyPressed(KeyEvent i) {
Keys.keySet(i.getKeyCode(), true);
}
public void keyReleased(KeyEvent i) {
Keys.keySet(i.getKeyCode(), false);
}
}
Try to use Toolkit.getScreenSize()
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
For resizing the image you can use simple imgscalr library
BufferedImage scaledImage = Scalr.resize(myImage, 100);
Determining the screen size...
How to set present screensize in Java Swing?
Full-Screen Exclusive Mode API
Scaling the image...
Java: maintaining aspect ratio of JPanel background image
Quality of Image after resize very low -- Java
The Perils of Image.getScaledInstance()
I'd also discourage the use KeyListener and encourage the use of the Key Bindings API. See How to use key bindings for more details
Using the default Graphics object from the java.awt package, you can use the drawImage method with 10 parameters:
int destinationWidth = ...;
int destinationHeight = ...;
g.drawImage(originalImage, 0, 0, destinationWidth, destinationHeight, 0, 0, originalImage.getWidth(null), originalImage.getHeight(null), null);
That way your image will be scaled and painted to g. Note that simply by using as in the example provided will stretch and deform your image if the aspect ratio of your window is different from the aspect ratio of the image.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am working on a game and I am getting this error for my code:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at com.mcserverpros.game.gfx.SpriteSheet.<init>(SpriteSheet.java:21)
at com.mcserverpros.game.Game.<init>(Game.java:32)
at com.mcserverpros.game.Game.main(Game.java:146)
This is my Game.java class:
package com.mcserverpros.game;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import com.mcserverpros.game.gfx.SpriteSheet;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 3;
public static final String NAME = "Game";
private JFrame frame;
public boolean running = false;
public int tickCount = 0;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer())
.getData();
public SpriteSheet spriteSheet = new SpriteSheet("/sprite_sheet.png");
public Game() {
setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public synchronized void start() {
running = true;
new Thread(this).start();
}
public synchronized void stop() {
running = false;
}
public void run() {
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D / 60D;
int frames = 0;
int ticks = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
boolean shouldRender = false;
while (delta >= 1) {
ticks++;
tick();
delta -= 1;
shouldRender = true;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (shouldRender) {
frames++;
render();
}
if (System.currentTimeMillis() - lastTimer >= 1000) {
lastTimer += 1000;
System.out
.println(ticks + " ticks" + ", " + frames + " frames");
frames = 0;
ticks = 0;
}
}
}
public void tick() {
tickCount++;
for (int i = 0; i < pixels.length; i++) {
pixels[i] = i + tickCount;
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public static void main(String[] args) {
new Game().start();
}
}
And this is my SpriteSheet.java class
package com.mcserverpros.game.gfx;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpriteSheet {
public String path;
public int width;
public int height;
public int[] pixels;
public SpriteSheet(String path) {
BufferedImage image = null;
try {
image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
} catch (IOException e) {
e.printStackTrace();
}
if (image == null) {
return;
}
this.path = path;
this.width = image.getWidth();
this.height = image.getHeight();
pixels = image.getRGB(0, 0, width, height, null, 0, width);
for (int i = 0; i < pixels.length; i++) {
pixels[i] = (pixels[i] & 0xff) / 64;
}
for (int i = 0; i < 8; i++) {
System.out.println(pixels[i]);
}
}
}
Check this line:
ImageIO.read(SpriteSheet.class.getResourceAsStream(path))
It seems that SpriteSheet.class.getResourceAsStream(path) is returning a null value. It's quite possible that path isn't pointing to an actual file in the filesystem. Notice that you're passing "/sprite_sheet.png", that's a path relative to the source code's directory. Take a look at this post to get an idea of how you can build a relative path that works. If all else fails you could use an absolute path, but that won't be portable.
I'm having an issue with my 2D game that I am following a tutorial for. I've scanned my code several times and cannot seem to resolve it. Sorry if my question sounds stupid, but I do welcome any help whatsoever.
Here's my source:
package game;
import gfx.SpriteSheet;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable
{
private static final long serialVersionUD = 1L;
public static final int WIDTH = 160;
public static final int HEIGHT = WIDTH/12*9;
public static final int SCALE = 3;
public static final String NAME = "Game";
private JFrame frame;
public boolean running = false;
public int tickCount = 0;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
private SpriteSheet spriteSheet = new SpriteSheet("SpriteSheet.png");
public Game()
{
setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private synchronized void start()
{
running = true;
new Thread(this).start();
}
private synchronized void stop()
{
running = false;
}
public void run()
{
long lastTime = System.nanoTime();
double nsPerTick = 1000000000D / 60D;
int ticks = 0;
int frames = 0;
long lastTimer = System.currentTimeMillis();
double delta = 0;
while(running)
{
long now = System.nanoTime();
delta += (now - lastTime) / nsPerTick;
lastTime = now;
boolean shouldRender = false;
while(delta >= 1)
{
ticks++;
tick();
delta -= 1;
shouldRender = true;
}
try {
Thread.sleep(2);
} catch (InterruptedException ex) {
}
if(shouldRender)
{
frames++;
render();
}
if(System.currentTimeMillis() - lastTimer >= 1000)
{
lastTimer += 1000;
System.out.println(frames + ", " + ticks);
frames = 0;
ticks = 0;
}
}
}
//Updates all of internal variables and logic and stuff.
public void tick()
{
tickCount++;
for(int i = 0; i < pixels.length; i++)
{
pixels [i] = i + tickCount;
}
}
//prints the updated logic.
public void render()
{
BufferStrategy bs = getBufferStrategy();
if(bs == null)
{
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
//Main method
public static void main(String[]args)
{
new Game().start();
}
}
package gfx;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpriteSheet
{
public String path;
public int width;
public int height;
public int[] pixels;
public SpriteSheet(String path)
{
BufferedImage image = null;
try
{
image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
} catch (IOException e)
{
e.printStackTrace();
}
if(image == null)
{
return;
}
this.path = path;
this.width = image.getWidth();
this.height = image.getHeight();
pixels = image.getRGB(0, 0, width, height, null, 0, width);
for(int i = 0; i < pixels.length; i++)
{
pixels[i] = (pixels[i] & 0xff / 64);
}
for(int i = 0; i < 8; i++)
{
System.out.println(pixels[i]);
}
}
}
And here's a link to my video tutorial I'm using: Tutorial
I'm using eclipse on a 64 bit operating system(Windows).
Again, any help would be greatly appreciated, and thank you.
EDIT:
Error message:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1348)
at gfx.SpriteSheet.<init>(SpriteSheet.java:21)
at game.Game.<init>(Game.java:34)
at game.Game.main(Game.java:144)
Sorry, forgot error message. XD
The error message is telling you what's wrong: Your image path is wrong. The image path must be given relative to the class files location.
I'm making an rpg with a custom pixel engine, and when I try to run it I just get a NullPointerException and I know why, but when I try to initialize that variable I get another one in a different location and I fix that and now it won't run at all and I still get a NullPointerException. This is the class that gets an error, and the console tells me that the error is on the line that says screen.render();
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import sprites.SpriteSheetLoader;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public static final int HEIGHT = 120;
public static final int WIDTH = 120;
public static final int SCALE = 3;
public static final String NAME = "TypicalRPG";
public SpriteSheetLoader loader;
private BufferedImage img = new BufferedImage(WIDTH * SCALE, HEIGHT * SCALE, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
private boolean running = false;
private Screen screen = new Screen(WIDTH, HEIGHT, loader);
Random random = new Random();
public void start(){
running = true;
new Thread(this).start();
}
public static void main(String args[]){
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame jf = new JFrame(NAME);
jf.add(game);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);
jf.setResizable(true);
game.start();
}
public void run(){
while(running){
tick();
render();
try{
Thread.sleep(5);
}
catch(InterruptedException e){ e.printStackTrace(); }
}
}
public void stop(){ running = false; }
public void tick(){
screen.render(0, 0, 0, 16, 16);
}
public void render(){
BufferStrategy bs = getBufferStrategy();
if(bs == null){
createBufferStrategy(3);
requestFocus();
return;
}
for(int i = 0; i < screen.pixels.length; i++){
pixels[i] = screen.pixels[i];
}
Graphics g = bs.getDrawGraphics();
g.drawImage(img, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public void init(){
BufferedImage sheet = null;
try {
sheet = ImageIO.read(Game.class.getResourceAsStream("res/tiles.png"));
}
catch (IOException e) {
e.printStackTrace();
}
loader = new SpriteSheetLoader(sheet);
screen = new Screen(WIDTH, HEIGHT, loader);
}
}
and this is the class that has render():
import sprites.SpriteSheetLoader;
public class Screen{
public int[] pixels;
private SpriteSheetLoader loader;
private int w, h;
int xoff = 0, yoff = 0;
public Screen(int w, int h, SpriteSheetLoader loader){
this.loader = loader;
this.w = w;
this.h = h;
pixels = new int[w * h];
}
public void render(int xpos, int ypos, int tile, int width, int height){
loader.grabTile(tile, width, height);
xpos -= xoff;
ypos -= yoff;
for(int y = 0; y < height; y++){
if(ypos + y < 0 || ypos + y >= h) continue;
for(int x = 0; x < width; x++){
if(xpos + x < 0 || xpos + x >= w) continue;
int col = loader.pixels[x + (y * height)];
if(col != -65281) pixels[(x + xpos) + (y + ypos)] = col;
}
}
}
}
Seems like you never initiate the loader in your first class.
You define your variables like this:
public SpriteSheetLoader loader;
private Screen screen = new Screen(WIDTH, HEIGHT, loader);
Hence, you pass a null-object to your Screen. And from there you try to call a method on that null-object:
loader.grabTile(tile, width, height);
You have only declared loader, but never initiated it.
public SpriteSheetLoader loader;