Error In Java: IllegalArgumentException [closed] - java

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.

Related

Bricks array not forming

I'm having troubles with my Brick Breaker game that I am making in my 12th grade programming class.
Currently, it seems that only the brick in Bricks.render does draw. When I output what the X and Y of the bricks should be it puts each brick in the right position. So I believe I'm drawing it wrong.
MCVE:
Game.java
package main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable {
// variables
private static final long serialVersionUID = 1L;
public static final int WIDTH = 480, HEIGHT = 600, SCALE = 1;
public final String TITLE = "Brick Breaker";
private static boolean running = false;
private Thread thread;
private int fpsDisplay = 0;
Bricks[] level1 = new Bricks[16];
// creates a new Game (which creates the game window)
public static void main(String[] args) {
new Game();
}
public Game() {
new GameWindow(WIDTH, HEIGHT, SCALE, TITLE, this);
System.out.println("[" + TITLE + " has started.]");
}
// called in GameWindow, starts the thread and game loop
public synchronized void start() {
if (running)
return;
thread = new Thread(this);
thread.start();
running = true;
}
public void init() {
this.createlevel1();
}
// used for updating what's happening in the game
private void tick() {
}
// renders the graphics
private void render() {
// --------- INIT GRAPHICS --------- //
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
FontMetrics fontMetrics = g2d.getFontMetrics();
// --------- INIT GRAPHICS --------- //
// clearing background
super.paint(g);
g2d.setColor(Color.black);
g2d.drawString(Integer.toString(fpsDisplay) + " FPS",
WIDTH - 9 - fontMetrics.stringWidth(Integer.toString(fpsDisplay) + " FPS"), 14);
// render level 1
for (int i = 0; i < 16; i++) {
level1[i].render(g);
}
// render level 1
// ---------
g.dispose();
g2d.dispose();
bs.show();
// ---------
}
public void createlevel1() {
int brickCount = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
level1[brickCount] = new Bricks(50 + i * 100, 50 + j * 100);
System.out.println("X: " + (50 + i * 100) + " Y: " + (50 + j * 100));
brickCount++;
}
}
}
// 60 tps game loop
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("Ticks: " + updates + ", FPS: " + frames);
fpsDisplay = frames;
updates = 0;
frames = 0;
}
}
stop();
}
// called at the end of the loop, stops the thread
public synchronized void stop() {
try {
thread.join();
running = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Bricks.java
package main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
#SuppressWarnings("unused")
public class Bricks {
private int x, y, w, h;
private Boolean isAlive;
private Color randColour;
public Bricks(int x, int y) {
x = this.x;
y = this.y;
w = 75;
h = 25;
isAlive = true;
randColour = Color.blue;
}
public void render(Graphics g) {
g.setColor(randColour);
g.fillRect(x, y, w, h);
}
}
GameWindow.java
package main;
import java.awt.Canvas;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class GameWindow extends Canvas {
private static final long serialVersionUID = -5131420759044457697L;
public GameWindow(int WIDTH, int HEIGHT, int SCALE, String TITLE, Game game) {
JFrame frame = new JFrame(TITLE);
frame.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
frame.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
frame.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
try {
frame.setIconImage(ImageIO.read(new File("res/Brick-icon.png")));
} catch (IOException e) {
frame.setIconImage(null);
e.printStackTrace();
System.out.println("ICON ERROR: Icon image not found. (Default Icon is set.)");
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(game);
frame.pack();
game.start();
// displays the window 400ms later to allow for the game to fully load
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frame.setVisible(true);
}
}
In Bricks.java:
x = this.x;
y = this.y;
should be:
this.x = x;
this.y = y;

Canvas doesn't update after drawing images

I am designing a game in Java. I'm using a bit of code I found at java-gaming.org, and it seems to be working strangely.
When I run the loop as given, it will update my canvas correctly. However, I don't want it to always be updating my "background" so to speak. To fix this I had it only run once. Now it appears to run, but does not display the image I painted.
I've uploaded screenshots of the program running once (broken) and the program running continuously (working). See them on imgur.
tldr; Everything appears to run, but it doesn't display anything in my frame. see code below.
package main;
//imports...
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameEngine implements Runnable {
//declare variables...
final static int B_HEIGHT = 20;
final static int B_WIDTH = 20;
private int cellWidth = GameTester.WIDTH / B_WIDTH;
private int cellHeight = GameTester.HEIGHT / B_HEIGHT;
protected boolean init = true;
JFrame frame;
Canvas canvas;
BufferStrategy bufferStrategy;
Board gameBoard;
Generator gen;
long desiredFPS = 60;
long desiredDeltaLoop = (1000 * 1000 * 1000) / desiredFPS;
boolean running = true;
public GameEngine(int width, int height) {
//create the gamespace...
gameBoard = new Board(B_WIDTH, B_HEIGHT);
gen = new Generator();
gen.addWalls(gameBoard);
agents.Champion champ = new agents.Champion();
items.Item item = new items.Item();
gameBoard.placeChampion(champ);
gameBoard.placeItem(item);
//frame magic...
frame = new JFrame("Basic Game");
JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(width, height));
panel.setLayout(null);
canvas = new Canvas();
canvas.setBounds(0, 0, width, height);
canvas.setIgnoreRepaint(true);
panel.add(canvas);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
canvas.createBufferStrategy(2);
bufferStrategy = canvas.getBufferStrategy();
canvas.requestFocus();
}
//actual game mechanics...
public void run() {
long beginLoopTime;
long endLoopTime;
long currentUpdateTime = System.nanoTime();
long lastUpdateTime;
long deltaLoop;
//game loop...
while (running) {
beginLoopTime = System.nanoTime();
//this draws things
render();
lastUpdateTime = currentUpdateTime;
currentUpdateTime = System.nanoTime();
//update magic...
update((int) ((currentUpdateTime - lastUpdateTime) / (1000 * 1000)));
endLoopTime = System.nanoTime();
deltaLoop = endLoopTime - beginLoopTime;
if (deltaLoop <= desiredDeltaLoop) {
try {
Thread.sleep((desiredDeltaLoop - deltaLoop) / (1000 * 1000));
} catch (InterruptedException e) {
// Do nothing
}
}
}
}
//creates g object...
private void render() {
Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
g.clearRect(0, 0, GameTester.WIDTH, GameTester.HEIGHT);
render(g);
g.dispose();
bufferStrategy.show();
}
// does nothing important...
private double x = 0;
protected void update(int deltaTime) {
if (GameTester.dbglvl > 1) {
System.out.println("update called");
}
x += deltaTime * 0.2;
while (x > 500) {
x -= 500;
}
}
// ACTUAL GAME DRAWING MECHANISM...
protected void render(Graphics2D g) {
//first run
if (init) {
renderinit(g);
} else {
//every other time after first run
}
}
//first run (generates game board)
protected void renderinit(Graphics2D g) {
BufferedImage img = null;
//loop through 2d array
for (int row = 0; row < gameBoard.getWidth(); row++) {
for (int col = 0; col < gameBoard.getHeight(); col++) {
//get image path
String str = gameBoard.getSpace(row, col).getPath();
//debug info
if (GameTester.dbglvl > 1) {
System.out.println(gameBoard.getSpace(row, col).getPath());
}
//get the image to be rendered
try {
img = ImageIO.read(new File(str));
} catch (IOException e) {
if (GameTester.dbglvl > 0) {
System.out
.println("image get failed - image specified: "
+ str + " ");
}
}
if (GameTester.dbglvl > 1) {
System.out.println("Image Destination: (" + row * cellWidth
+ ", " + col * cellHeight + ")");
}
//draws given image
g.drawImage(img, row * cellWidth, // DX1
col * cellHeight, // DY1
(row * cellWidth) + cellWidth, // DX2
(col * cellHeight) + cellHeight, // DY2
0, // SX1
0, // SY1
img.getWidth(), // SX2
img.getHeight(), // SY2
null);
}
}
//done with first time run
init = false;
if (GameTester.dbglvl > 0) {
System.out.println("Board Rendered");
}
}
}

(Java) Getting error with 2D Game

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.

Java - Eclipse IDE, program terminated by a pointer exception error

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.

Variable stops being set after "if" statement is added [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a input class. When up is pressed it sets player.hasJumped = true; and when hasJumped is true, it changes dy to -3 in the player class. The problem is, that hasJumped is being set to true, but the variable is not changing. I can't really figure out why this is happening. This is a short sample of my code, I can provide more if needed.
InputHandler.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class InputHandler implements KeyListener{
Player player = new Player();
private boolean[] keys = new boolean[120];
public boolean up;
public void tick(){
up = keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];
if(player.jumpReady){
if(up){
player.inAir = true;
System.out.println("JUMPED " + player.inAir);
}
}
}
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
Player.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Player {
int x;
int y;
int dx;
public long xElapsed = 0;
public int dy;
int width = 50;
int height = 75;
public int hangTime = 0;
int maxHangTime = 100;
int nextX = 1000;
public int playerSpeed = 7;
public int coinsCollected = 0;
public boolean isMoving = true;
public boolean hasJumped = false;
public boolean jumpReady = true;
public boolean hasCollided = false;
public boolean inAir = false;
private BufferedImage moving1 = null;
private String path1 = "res/player_moving_1.png";
public Player(){
try {
moving1 = ImageIO.read(new File(path1));
}catch (IOException e) {
e.printStackTrace();
System.err.println("Could not load image " + moving1 + " at path" + path1);
}
x = 150;
y = 250;
}
public void render(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(moving1, x, y, null);
}
public void move(){
x = x + dx;
y = y + dy;
xElapsed++;
if(xElapsed == nextX){
upSpeed();
nextX += 1000;
}
if(inAir){
System.out.println("test");
dy = -3;
}
}
public void paint(Graphics g){
g.setColor(Color.RED);
g.fillRect(x, y, width, height);
}
public void upSpeed(){
playerSpeed++;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public long getXElapsed(){
return xElapsed;
}
public double getSpeed(){
return playerSpeed;
}
public int getNextX(){
return nextX;
}
public int getCoinsCollected(){
return coinsCollected;
}
public Rectangle bounds(){
return (new Rectangle(x, y, width, height));
}
}
Game.java
private static final long serialVersionUID = 1L;
public static final int WIDTH = 350;
public static final int HEIGHT = WIDTH / 16 * 9;
public static final int SCALE = 2;
private Thread thread;
private JFrame frame;
private InputHandler input;
private boolean running = false;
private Screen screen;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
Player player = new Player();
public Game() {
Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
setPreferredSize(size);
screen = new Screen(WIDTH, HEIGHT);
frame = new JFrame();
input = new InputHandler();
addKeyListener(input);
setFocusable(true);
}
public void run() {
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
final double ns = 1000000000.0 / 60.0;
double delta = 0;
int frames = 0;
int ticks = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
ticks++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println(ticks + " tps, " + frames + " fps");
ticks = 0;
frames = 0;
}
}
stop();
}
public void tick(){
input.tick();
player.move();
collision();
obstacleHole.move();
obstacleWolf.move();
coin.move();
}
Within Game.java pass the object player as argument within the constructor of InputHandler as follows:
public Game() {
Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
setPreferredSize(size);
screen = new Screen(WIDTH, HEIGHT);
frame = new JFrame();
input = new InputHandler(player);//pass player object as argument
addKeyListener(input);
setFocusable(true);
}
And change the InputHandler class as follows:
public class InputHandler implements KeyListener{
Player player ; //Don't initialize it.
//Create a parametric constructor
public InputHandler(Player player)
{
this.player = player;
}
//...And then proceed with other stuffs
}

Categories