I am trying out something new and I am wondering if this is valid and is not working because of some other code glitch.

Graphics class:

import java.awt.*;
import javax.swing.JPanel;


public class Drawing extends JPanel{

	KeyCommands kc = new KeyCommands ();
	public void startGraphics (){
		System.out.println ("Adding KeyListener");
		addKeyListener (kc);
		System.out.println ("Taking Focus");
		requestFocus();
		repaint();
	}
	
	public void paintComponent (Graphics g){
		super.paintComponents(g);
		g.fillRect(15,40, 40, 40);
	}
	
	
}

KeyListener portion

import java.awt.event.*;

public class KeyCommands implements KeyListener{

	CharacterAnimation charAnimate = new CharacterAnimation ();
	
	Frame frame;
	String direction;
	public void setUpWindow(Frame f){
		frame = f;
		System.out.println ("Frame Set up");
	}
	
	
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		int key = e.getKeyCode();
		System.out.println ("Key Pressed");
		if (key == KeyEvent.VK_UP){
			direction = "UP";
		}
		else if (key == KeyEvent.VK_DOWN){
			direction = "DOWN";
		}
		else if (key == KeyEvent.VK_LEFT){
			direction = "LEFT";
		}
		else if (key == KeyEvent.VK_RIGHT){
			direction = "RIGHT";
		}
		else if (key == KeyEvent.VK_ESCAPE){
			System.out.println ("Escape Pressed");
			frame.closeWindow();
		}
		
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

}

I am trying to separate the KeyListener from the drawing class. Then I want to add the KeyListener class to the drawing class, so they act like one code, but they are separate. I am assuming that when I add it and the drawing class has focus and I press a button it will realize that it is a key event and then go to the KeyCommands class to see what it needs to do. I ran into this problem when I tried closing the window with escape. That is why only that one like has a println.

Thanks for any help.

again same suggestion as I gave you more than twice

Are you referring to the

grabFocus();

or

requestFocus();

lines? I have that in my code. I believe that it is the

addKeyListener(kc);

that is the issue, or something in the KeyCommands class.

I am now getting a null pointer exception. I have checked the image and the coordinates, and the repaint.

animation for character

import java.io.*;
import java.awt.*;
import java.awt.image.*;

import javax.imageio.*;

public class CharacterAnimation extends Character implements Runnable{

	int animationNumber = 1;
	public void run() {
		// TODO Auto-generated method stub
		
		if (direction.equals ("UP")){
			for (int i = 0; i < 3; i++){
				try {
					BufferedImage img = ImageIO.read(new File ("Images/image.png"));
					character = img.getSubimage((animationNumber * 32), 96, 32, 32);
					animationNumber ++;
					if (animationNumber == 3){
						animationNumber = 0;
					}
					draw.reDraw();
					Thread.sleep(50);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				lastDirection = "UP";
			}
			
			
		}
		else if (direction.equals ("DOWN")){
			for (int i = 0; i < 3; i++){
				try {
					BufferedImage img = ImageIO.read(new File ("Images/image.png"));
					character = img.getSubimage((animationNumber * 32), 0, 32, 32);
					animationNumber ++;
					if (animationNumber == 3){
						animationNumber = 0;
					}
					draw.reDraw();
					Thread.sleep(50);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				lastDirection = "Down";
			}
		}
		else if (direction.equals ("LEFT")){
			for (int i = 0; i < 3; i++){
				try {
					BufferedImage img = ImageIO.read(new File ("Images/image.png"));
					character = img.getSubimage((animationNumber * 32), 32, 32, 32);
					animationNumber ++;
					if (animationNumber == 3){
						animationNumber = 0;
					}
					draw.reDraw();
					Thread.sleep(50);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				lastDirection = "LEFT";
			}
		}
		else if (direction.equals ("RIGHT")){
			for (int i = 0; i < 3; i++){
				try {
					BufferedImage img = ImageIO.read(new File ("Images/image.png"));
					character = img.getSubimage((animationNumber * 32), 64, 32, 32);
					animationNumber ++;
					if (animationNumber == 3){
						animationNumber = 0;
					}
					draw.reDraw();
					Thread.sleep(50);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				lastDirection = "RIGHT";
			}
		}

	}

	public void setUpKeyCommand (KeyCommands kCommands){
		keyCom = kCommands;
	}
	public void setDirection (String dir){
		direction = dir;
	}
	
	
}

character class

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.*;

public class Character {

	Drawing draw;
	String lastDirection;
	Image character;
	int maxHealth;
	int health;
	String direction;
	
	KeyCommands keyCom;
	
	int x = 10,y = 10;
	
	Character (){
		maxHealth = 6;
		health = 6;
		BufferedImage img;
		try {
			img = ImageIO.read(new File ("Images/image.png"));
			character = img.getSubimage (32,0,32,32);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public int getHealth (){
		return health;
	}
	public String getDirection (){
		return direction;
	}

	public void passInDrawing(Drawing drawing) {
		// TODO Auto-generated method stub
		draw = drawing;
	}

	public Image getCharacter() {
		// TODO Auto-generated method stub
		System.out.println (character);
		return character;
	}
	
}

Drawing class

import java.awt.*;
import javax.swing.JPanel;


public class Drawing extends JPanel{

	KeyCommands kc = new KeyCommands ();
	Character player = new Character ();
	public void startGraphics (){
		System.out.println ("Adding KeyListener");
		addKeyListener (kc);
		System.out.println ("Taking Focus");
		player.passInDrawing(this);
		grabFocus();
		repaint();
	}
	
	public void paintComponent (Graphics g){
		super.paintComponent(g);
		g.drawImage(player.getCharacter(), player.x, player.y, 32, 32, null);
	}

	public void reDraw() {
		// TODO Auto-generated method stub
		repaint();
	}
	
	
}

Here is the error

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at CharacterAnimation.run(CharacterAnimation.java:45)
	at KeyCommands.actionPerformed(KeyCommands.java:62)
	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$000(Unknown Source)
	at java.awt.EventQueue$1.run(Unknown Source)
	at java.awt.EventQueue$1.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.AccessControlContext$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)

This happens after the key is pressed.

not about KeyBindings

It kind of is key bindings, as I understand it. because I say which direction it is going ("UP", "DOWN", etc.). And this time I do not want it to go diagonal. The movement will be like pokemon. And I still don't know where the null pointer exception is.

I didn't see any constructor from Timer to the KeyCommands,

... I still don't know where the null pointer exception is.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at CharacterAnimation.run(CharacterAnimation.java:45)

Now then, that wasn't so hard was it?

CharacterAnimation.java: line 45 is draw.reDraw(); , so the only way to get an NPE from that is if draw is null - ie you have not initalised it.

I still don't understand, because I pass it into Character.java which looks like this

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.*;

public class Character {

	Drawing draw;
	String lastDirection;
	Image character;
	int maxHealth;
	int health;
	String direction;
	
	KeyCommands keyCom;
	
	int x = 10,y = 10;
	
	Character (){
		maxHealth = 6;
		health = 6;
		BufferedImage img;
		try {
			img = ImageIO.read(new File ("Images/image.png"));
			character = img.getSubimage (32,0,32,32);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public int getHealth (){
		return health;
	}
	public String getDirection (){
		return direction;
	}

	public void passInDrawing(Drawing drawing) {
		// TODO Auto-generated method stub
		System.out.println ("Assigning Drawing");
		draw = drawing;
		System.out.println ("Done!");
	}

	public Image getCharacter() {
		// TODO Auto-generated method stub
		System.out.println (character);
		return character;
	}
	
}

And it says that it is done passing in Drawing and assigning it to draw. I even moved the passInDrawing method above addKeyListener (kc) to make sure that something in keyCommands wasn't messing with it, but I still get the error.

Maybe the value you are passing in is null?

I have added in printlns before sending in drawing and after assigning drawing to draw and here is what I got

Drawing[,0,50,550x460,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
Assigning Drawing
Done adding Drawing[,0,50,550x460,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.