Error when calling method from other class [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm getting an error when I call my refresh() method from another class.
public void refresh() {
repaint();
}
It's a JFrame that the refresh() is in and I'm calling it from a normal class. The error is a Null Pointer, and it is on my level.refresh(), as well as as public void refresh().
What I am trying to do is working completely fine, but I'm getting this error
Player class`package entity.player;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import level.Level;
public class Player {
public static Image playerImgLeft = new ImageIcon(
"resources/Player/left/player_anim1_left.png").getImage();
public static Image playerImgRight = new ImageIcon(
"resources/Player/right/player_anim1_right.png").getImage();
public static Level levelp;
public int x = 0;
public int y = 0;
public int dy = 0;
public int dx = 0;
// Direction = right
public int direction = 0;
public Player() {
x = 10;
y = 10;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImageLeft() {
return playerImgLeft;
}
public Image getImageRight() {
return playerImgRight;
}
public void move() {
x = x + dx;
y = y + dy;
}
public void keyPressed(KeyEvent key) {
if (key.getKeyCode() == KeyEvent.VK_A) {
dx = -1;
direction = 1;
System.out.println("left");
levelp.refresh();
}
if (key.getKeyCode() == KeyEvent.VK_D)
dx = 1;
direction = 0;
if (key.getKeyCode() == KeyEvent.VK_W)
dy = -1;
if (key.getKeyCode() == KeyEvent.VK_S)
dy = 1;
}
public void keyReleased(KeyEvent key) {
if (key.getKeyCode() == KeyEvent.VK_A)
dx = 0;
if (key.getKeyCode() == KeyEvent.VK_D)
dx = 0;
if (key.getKeyCode() == KeyEvent.VK_W)
dy = 0;
if (key.getKeyCode() == KeyEvent.VK_S)
dy = 0;
}
}
Level class:
package level;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
import entity.player.Player;
public class Level extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
public static int level = 0;
Player player;
public Timer time;
public Image img;
public Level() {
this.setVisible(true);
setFocusable(true);
player = new Player();
this.addKeyListener(new LevelKeyListener());
ImageIcon i = new ImageIcon("");
img = i.getImage();
time = new Timer(5, this);
time.start();
}
public void actionPerformed(ActionEvent e) {
player.move();
repaint();
revalidate();
}
public void refresh () {
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g.drawImage(img, 0, 0, null);
if(player.direction == 0) {
g2d.drawImage(player.getImageRight(), player.getX(), player.getY(), null);
} else if(player.direction == 1) {
g2d.drawImage(player.getImageLeft(), player.getX(), player.getY(), null);
}
}
private class LevelKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
player.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
player.keyReleased(e);
}
}
}
`

As was suspected, your levelp variable points to nothing (is null).
When you look at this line you'll see that you're trying to call the refresh() method on a variable that isn't actually referencing anything:
levelp.refresh();
which is just declared as
public static Level levelp;
without any code that actually creates a Level object (ergo: you are trying to call a method on a reference that points to null).
Try creating an immediate object like this:
public static Level levelp = new Level();
I also encourage you to read through this post so you understand how and when NullPointerExceptions occur!

Related

Why my 2-D character moves up, even though I did not even pressed keys? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed last month.
Improve this question
I was learning how to make 2-D games for self-development by reference to the [https://www.youtube.com/watch?v=VpH33Uw-_0E&list=PL_QPQmz5C6WUF-pOQDsbsKbaBZqXj4qSq&index=2]
So at the below, you will see three simple class codes. I checked every line but still, when I run the game, white rectangle directly starts to move up. Any help is great kindness.
Main Class
package main;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setTitle("MY 2-D GAME");
GamePanel gamePanel = new GamePanel();
window.add(gamePanel);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
gamePanel.startGameThread();
}
}
GamePanel Class
package main;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class GamePanel extends JPanel implements Runnable{
private static final int FPS = 60;
final int originalTileSize = 16;
final int scale = 3;
final int tileSize = originalTileSize * scale; // 48x48
final int maxScreenCol = 16;
final int maxScreenRow = 12;
final int screenWidth = tileSize * maxScreenCol;
final int screenHeight = tileSize * maxScreenRow;
KeyHandler key_Handler = new KeyHandler();
Thread gameThread;
int player_x = 100;
int player_y = 100;
int player_speed = 4;
public GamePanel() {
this.setPreferredSize(new Dimension(screenWidth,screenHeight));
this.setBackground(Color.black);
this.setDoubleBuffered(true);
this.addKeyListener(key_Handler);
this.setFocusable(true);
}
public void startGameThread() {
gameThread = new Thread(this);
gameThread.start();
}
public void run() {
double drawInterval = 1000000000/FPS;
double delta = 0;
long lastTime = System.nanoTime();
long current_time;
while (gameThread != null) {
current_time = System.nanoTime();
delta += (current_time - lastTime) / drawInterval;
lastTime = current_time;
if (delta >= 1) {
update();
repaint();
delta--;
}
}
}
public void update() {
if (key_Handler.upMove = true) {
player_y -= player_speed;
}
else if (key_Handler.downMove = true) {
player_y += player_speed;
}
else if (key_Handler.leftMove = true) {
player_x -= player_speed;
}
else if (key_Handler.rightMove = true) {
player_x += player_speed;
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.white);
g2.fillRect(player_x,player_y, tileSize, tileSize);
g2.dispose();
}
}
KeyHandler Class
package main;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyHandler implements KeyListener{
public boolean upMove, downMove, leftMove, rightMove;
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_W) {
upMove = true;
}
if (code == KeyEvent.VK_S) {
downMove = true;
}
if (code == KeyEvent.VK_A) {
leftMove = true;
}
if (code == KeyEvent.VK_D) {
rightMove = true;
}
}
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
int code = e.getKeyCode();
if (code == KeyEvent.VK_W) {
upMove = false;
}
if (code == KeyEvent.VK_S) {
downMove = false;
}
if (code == KeyEvent.VK_A) {
leftMove = false;
}
if (code == KeyEvent.VK_D) {
rightMove = false;
}
}
}
After a quick skim, I think I found the culprit:
if (key_Handler.upMove = true) {
player_y -= player_speed;
}
Remember that for comparisons in C-style languages, you need double equals (==), or better yet, just put key_handler.upMove in the parenthesis alone because it is already a boolean. So change your if statements to look like the following:
if (key_Handler.upMove) { // or key_Handler.upMove == true if you prefer.
player_y -= player_speed;
}
Your code was assigning key_handler.upMove to true and using that in your if statement.
Rather than using:
if (key_Handler.upMove = true) {
player_y -= player_speed;
}
Use:
if (key_Handler.upMove) {
player_y -= player_speed;
}
And the same for other conditions as well.

Why does it wants the method to be static?

I am building my first game, relying heavily on various tutorials and guides on the Java website, and I have come across a problem.
In my game engine, I want to call the Player.update() method, but it says it has to be static (cannot make static reference to non-static method)
However, the method calling it is not static. Can anyone tell me why it requires it to be static? It doesn't require the only other method in Update to be static.
package Main;
import java.awt.*;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import Graphics.Assets;
import Sprites.Player;
#SuppressWarnings("serial")
public class Game extends JPanel
implements Runnable, KeyListener{
//TEST CODE
private int x = 0;
private int y = 0;
private int dY = 1;
private int dX = 1;
public void moveBall() {
x = x + dX;
y = y + dY;
if(x > WIDTH - 28) {
dX = -1;
}
if(y > HEIGHT) {
dY = -1;
}
if(x < 0) {
dX = 1;
}
if(y < 10) {
dY = 1;
}
}
//dimensions
public static final int WIDTH = 400;
public static final int HEIGHT = 300;
public static final int SCALE = 2;
//game thread
private Thread thread;
private boolean running;
private int FPS = 60;
private long targetTime = 1000 / FPS;
//image
private BufferedImage image;
private Graphics2D g;
//Constructor
public Game () {
super();
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setFocusable(true);
requestFocus();
}
public void addNotify() {
super.addNotify();
if(thread == null) {
thread = new Thread(this);
addKeyListener(this);
thread.start();
}
}
private void init () {
image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D)image.getGraphics();
running = true;
Assets.init();
}
public void run() {
init();
long start;
long elapsed;
long wait;
//game loop
while(running){
start = System.nanoTime();
update();
draw(g);
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if(wait < 0) wait= 5;
try {
Thread.sleep(wait);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
private void update() {
moveBall();
Player.update();
}
private void draw(Graphics g2d) {
super.paint(g2d);
Graphics2D g = (Graphics2D) g2d;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawString("Hello", x, y);
}
private void drawToScreen() {
Graphics g2 = getGraphics();
g2.drawImage(image, 0, 0, WIDTH * SCALE, HEIGHT * SCALE, null);
g2.dispose();
}
public void keyPressed(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
That is the main code. Now for the Player class.
package Sprites;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import Main.Game;
import Graphics.*;
public class Player extends Creature implements KeyListener{
private int dir;
public Player(Game game, float x, float y) {
super(game, x, y, Creature.DEFAULT_CREATURE_WIDTH, Creature.DEFAULT_CREATURE_HEIGHT);
dir = 0;
}
public void update() {
getInput();
move();
}
private void getInput() {
xMove = dir;
}
public void render(Graphics g) {
g.drawImage(Assets.player, (int) (x), (int) (y), width, height, null);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_A)
dir = -1;
if(e.getKeyCode() == KeyEvent.VK_D)
dir = 1;
else dir = 0;
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_A)
dir = 0;
if(e.getKeyCode() == KeyEvent.VK_D)
dir = 0;
}
public void keyTyped(KeyEvent e) {
}
}
Look at your method call:
Player.update();
That's calling it as if it's a static method - on the type, rather than on an instance of the type. Which player do you want to update? You don't seem to have any instances of it... you should almost certainly be creating an instance of Player within Game, and saving a reference to it.
You have called update() method of Player like this -
private void update() {
moveBall();
Player.update();
}
Here you did not create the object of Player. So the compiler expect the update() method is static. To resolve the problem you may do either of -
1. Make update() of player static. Or -
2. Create an instance/object of Player inside your Game class as a field/property before calling update() method of Player class -
Player aPlayer = new Player(.....);
.....
.....
.....
private void update(){
moveBall();
aPlayer.update();
}

Null Pointer Exception on GUI application using three classes

I'm working on a fairly basic game for myself. New to Java Swing but not to Cpp. Onto the problem at hand.
As I start to run the GUI app, I'm shot with a Null Pointer Exception and given four links where they happen(I use Eclipse as my IDE). But when I look at them I see no problem with the lines or anything around them.
So I came to see if any of you can spot what I can't find.
This class grabs the picture from the source folder and sets up the keys for giving movement.
import java.awt.event.KeyEvent;
import java.awt.Image;
import javax.swing.ImageIcon;
public class SPRITES
{
private int x_sped;
private int y_sped;
private int x;
private int y;
private Image sprite;
public SPRITES()
{
ImageIcon pine = new ImageIcon(this.getClass().getResource("Untitled.png")); //exception here, line 17
sprite = pine.getImage();
x = 0;
y = 0;
}
public void move()
{
x += x_sped;
y += y_sped;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public Image getImage()
{
return sprite;
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_A)
{
x_sped = -1;
}
if(key == KeyEvent.VK_D)
{
x_sped = 1;
}
if(key == KeyEvent.VK_W)
{
y_sped = -1;
}
if(key == KeyEvent.VK_S)
{
y_sped = 1;
}
}
public void keyReleased(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_A)
{
x_sped = 0;
}
if(key == KeyEvent.VK_D)
{
x_sped = 0;
}
if(key == KeyEvent.VK_W)
{
y_sped = 0;
}
if(key == KeyEvent.VK_S)
{
y_sped = 0;
}
}
}
The second one is for getting the frame setting up with completely making the frame and finishing up the making of the movement.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Stage extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private Timer start_stop;
private SPRITES player;
public Stage()
{
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.black);
setDoubleBuffered(true);
player = new SPRITES();
start_stop = new Timer(5, this);
start_stop.start();
}
public void paint(Graphics character)
{
super.paint(character);
Graphics2D G2D = (Graphics2D) character;
G2D.drawImage(player.getImage(), player.getX(), player.getY(), this);
Toolkit.getDefaultToolkit().sync();
character.dispose();
}
public void actionPerformed(ActionEvent arg0)
{
player.move();
repaint();
}
private class TAdapter extends KeyAdapter
{
public void keyReleased(KeyEvent e)
{
player.keyReleased(e);
}
public void keyPressed(KeyEvent e)
{
player.keyPressed(e);
}
}
}
This last one should tie it all together...granted I knew how to fix the exception.
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Framing extends JFrame
{
public Framing()
{
add(new Stage());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
setLocationRelativeTo(null);
setTitle("FLY");
setResizable(false);
setVisible(true);
}
public static void main(String[] args)
{
new Framing();
}
}
What is causing these exceptions to happen? How can I fix the problem and what should I work on to avoid this happening again?
I think you are misreading the stacktrace from eclipse. All the links except for the first(The one at the top) is the call stack, which show the calls made to the place where you got a nullpointer exception.
Which fit because the code:
new Framing()
Calls
add(new Stage())
which calls
player = new SPRITES();
Which calls
ImageIcon pine = new ImageIcon(this.getClass().getResource("Untitled.png"));
And this is where your nullpointer exception is. My guess is that getResources("Untitled.png"); returns null which then causes the ImageIcon constructor to throw a nullpointer exception.

Can't figure out how to repaint

So I have this little project where I make the mario jump. But I can't figure out how to repaint it. If I do it in the Main class after a click, then the whole jumping will be very jerky.
I tried to do it at the end of my jump function but that did not work too.
Here is my code:
Main:
package klassid;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Main extends JComponent implements KeyListener, ActionListener{
static Hero hero;
Timer t = new Timer(500,this);
public static void main(String[] args) {
JFrame aken = new JFrame("Simple jumping simulator");
aken.setSize(600, 600);
aken.getContentPane().setBackground(new Color(255,255,255));
aken.getContentPane().add(new Main());
aken.setVisible(true);
aken.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hero.the_jump();
}
public Main(){
addKeyListener(this);
setFocusable(true);
t.start();
hero = new Hero(0, 320);
}
public void paintComponent(Graphics g){
hero.render(g, this);
g.setColor(Color.GREEN);
g.fillRect(0, 550, 600, 2);
}
#Override
public void keyPressed(KeyEvent e) {
hero.move(e.getKeyCode());
}
public void keyReleased(KeyEvent e) {
hero.move2(e.getKeyCode());
}
public void keyTyped(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {}
}
And my Hero class:
package klassid;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.Graphics;
public class Hero {
static Main main;
int y;
Image pilt = Toolkit.getDefaultToolkit().getImage("../mario.png");
private double height = 0, speed = 4;
public static final double gravity = 9.81;
private double x = 25;
private boolean left = false, right = false, up = false;
public Hero(int x, int y){
this.x = x;
this.y = y;
}
public void render(Graphics g, Main pohiKlass){
g.drawImage(pilt, (int) (x), (int) (500-(height*100)), 50, 50, pohiKlass);
}
public void the_jump() {
long previous = 0, start = 0;
while(true){
start= System.nanoTime();
if(previous != 0 && up){
double delta = start - previous;
height += (delta/1000000000) * speed;
speed -= (delta/1000000000) * gravity;
}
if(left)
x -= 3;
if(right)
x += 3;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(height < 0){
height = 0;
speed = 4;
up = false;
}
previous = start;
repaint();
}
}
public void move(int i){
if(i == 38)
up=true;
if(i == 37)
left=true;
if(i == 39)
right=true;
}
public void move2(int i){
if(i == 37)
left=false;
if(i == 39)
right=false;
}
}
I also tried to access the paintComponent in the_jump function but it did not work as I have no idea what kind of a parameter it expects.
How is this mess solvable?
The first line in your paintComponent method should be:
super.paintComponent(g);
JComponent will do a lot of things for you, but you need to explicitly call the super class method to do so. Take a look at the Oracle Documentation here.
You could call repaint() in your actionPerformed method, if you decrease the timer value to something very low. This will give you "continuous" repainting (as many times a second as you can reasonably perform).

How do you make a character jump, both on objects and just normal jump?

I'm kind of a beginner when it comes to java programming, and I have a project in school where I'm going to create a game much like Icy Tower. And my question is, how am I going to write to make the character stand on the ground and be able to jump up on objects?
Here's my code so far:
Part one
package Sprites;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class jumper {
private String jump = "oka.png";
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public jumper() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(jump));
image = ii.getImage();
x = 50;
y = 100;
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -5;
ImageIcon ii = new ImageIcon(this.getClass().getResource("oki.png"));
image = ii.getImage();
}
if (key == KeyEvent.VK_RIGHT){
dx = 5;
ImageIcon ii = new ImageIcon(this.getClass().getResource("oka.png"));
image = ii.getImage();
}
if (key == KeyEvent.VK_SPACE) {
dy = -5;
}
if (key == KeyEvent.VK_DOWN) {
dy = 5;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT){
dx = 0;
}
if (key == KeyEvent.VK_SPACE) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
}
Part two
package Sprites;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class board extends JPanel implements ActionListener {
private Timer klocka;
private jumper jumper;
public board() {
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.WHITE);
setDoubleBuffered(true);
jumper = new jumper();
klocka = new Timer(5, this);
klocka.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(jumper.getImage(), jumper.getX(), jumper.getY(), this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
jumper.move();
repaint();
}
private class TAdapter extends KeyAdapter {
public void keyReleased(KeyEvent e) {
jumper.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
jumper.keyPressed(e);
}
}
}
Part three
package Sprites;
import javax.swing.JFrame;
public class RType extends JFrame {
public RType() {
add(new board());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
setTitle("R - type");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new RType();
}
}
I really appreciate all the help I can get!
This might help. It's a set of tutorials aimed at helping people make tile-based games. Including side-on platform games. See http://www.tonypa.pri.ee/tbw/tut07.html. By the way, you're doing quite intensive image-loading stuff in the character movement methods. Don't do that. Cache the images first. Also, you can double-buffer your Canvas to make it smooth. See the code here for details.

Categories

Resources