I small maze game and I got a key Listener. I got it to work.

The problem I have is that i have a text box in the gui and Key Listener is added on to the that. but I want to set it so that when the window is set selected and key pressed , the keypress method to be called.

You can add another key listener to window, if you not sure how to do it just post your code so we can see what is going on to help you fast

well i have 10+ classes... i can send you a jar file... will that do?

also i wont be able to send it till tomorrow...

Nope, that will not work, compile class is not "readable" and I do not have time to decompile it, so dearly you need to drop in class in which you want to implement key listener for window

Just attach the KeyListener to your panel or whatever component you're using for the game screen as Peter suggested.

App class

public App (javax.swing.JFrame frame){
		super("Maze Program");
		_game = new Game();
		frame.getContentPane().add(_game.getColumn());
	}

gui class - the actual board

public class MazeGUI implements IBoardConstants {
.
.
.
public void addKeyListener(KeyListener listener) {
		//.addKeyListener(listener);
	}
.
.
.
}

Game class

public Game(){
.
.
.
               _mazeGUI.addKeyListener(new Key(nav)); 
.
.
.
}

key listener

package mazes.gui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JOptionPane;

/**
 * 
 * Moves the Navigator
 *
 * @author Rajijha Jayasinghe
 *
 * Created on: Nov 22, 2008
 *
 */

public class Key implements KeyListener{

	private Navigator _navigator;
	
	public Key(Navigator nav){
		_navigator = nav;
	}

	public void keyPressed(KeyEvent e) {
		moveAccordingToKey(e);
	}


	public void keyReleased(KeyEvent e) {
	}


	public void keyTyped(KeyEvent e) {

	}
	
	public void moveAccordingToKey(KeyEvent e){
		int code = e.getKeyCode();
		if(code == 40){
			_navigator.moveDown();
		}
		if(code == 38){
			_navigator.moveUp();
		}
		if(code == 37){
			_navigator.moveLeft();
		}
		if(code == 39){
			_navigator.moveRight();
		}
		if(code <=36 || code >=41){
			JOptionPane.showMessageDialog(null,"Invaild key! You can only press arrow keys.");
		}
	}
}

You need to add the key listener to the visual component that is going to have the focus during game play. Just guessing from the incoherent fragments you posted, that may be whatever _game.getColumn() represents. Perhaps you need to read through the tutorial on key listeners and the focus system.

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.