Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2010
    Posts
    4
    Rep Power
    0

    Default Key Listener problem!

    SOLVED

    You have to add a

    setFocusable(true); in the init class

    Can someone tell me why my Key Listener (keyboard input) is not being recognized when i run my program on my laptop with eclipse but it works when it run it on my desktop at school?

    Here's the main code let me know if you want the other three classes but i dont think they are needed to solve this problem

    so far i know that the program is never even going to my


    Java Code:
    public void keyPressed(KeyEvent e){
    		switch(e.getKeyCode()){
    		case KeyEvent.VK_LEFT: left = true; break;
    		case KeyEvent.VK_RIGHT: right = true; break;
    		case KeyEvent.VK_1: state = PLAYING; break; 
    		case KeyEvent.VK_2: state = menu; break; 
    		case KeyEvent.VK_3: state = credits; break; 
    		}
    	}

    also i'm using java jre 7 on my laptop

    here's the full code

    Java Code:
    //The music was taken from the Skyrim Game
    //THe Vector<BadGuy> and Vector<Bullet> was made by a online user called "joyofprogram"
    
    import java.applet.AudioClip;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    
    public class SpaceInvaders extends JApplet implements KeyListener, Runnable{
    
    	public static final int PLAYING = 0; // if the game is in progress
    	public static final int WON = 1; // if the user wins
    	public static final int LOST = 2; // if the user loses
    	public static int menu = 3; // the menu screen
    	public static int credits = 4; // the credits screen
    	private Player player; //importing player class
    	private boolean left, right;  // making the variables that will move the player left and right
    	private Vector<BadGuy> badGuys; // the bad guys
    	private Vector<Bullet> bullets; // the bullets
    	private int state = menu; //setting the game to start on the menu
    	Font Mono=new Font("Monotype Corsiva",Font.BOLD,30); // creating a font type
    	Font Monosmall=new Font("Monotype Corsiva",Font.BOLD,15); // creating another font type
    	Font TimesnewRoman=new Font("Times New Roman",Font.BOLD,30); // creating another font type
    	private AudioClip audioClip; //Declares the variable for the song
    	private Button song1, stop; //Declares the variable for the two button which start and stop the song from playing
    	
    	@Override
    	public void init(){
    		addKeyListener(this);
    		audioClip = getAudioClip (getCodeBase (), "skyrim.wav"); //Imports the song
    		audioClip.loop();
    		setSize(500,300); //setting the screen size in the intro screen
    		player = new Player(getWidth()/2, getHeight()-Player.HeightofPlayer/2, getWidth());
    		badGuys = new Vector<BadGuy>();
    		for(int i = 0; i < 5; i++){
    			for(int j = 0; j < 4; j++){
    				BadGuy newBG = new BadGuy(BadGuy.WidthOfAlien*(2*i+2), BadGuy.HeightOfAlien*(2*j+2), getWidth(), false);
    				badGuys.add(newBG);
    			}
    		}
    
    		bullets = new Vector<Bullet>();
    
    		new Thread(this).start();
    	}
    
    	@Override
    	public void paint(Graphics graphics){
    		BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
    		Graphics g = image.getGraphics();
    		g.setColor(Color.BLACK);
    		g.fillRect(0, 0, getWidth(), getHeight());
    		player.draw(g);
    		for(int i = 0; i < badGuys.size(); i++)
    			badGuys.get(i).draw(g);
    		for(int i = 0; i < bullets.size(); i++)
    			bullets.get(i).draw(g);
    		if(state==menu){ //writing this for the intro menu screen
    			setSize(500,300); //setting the screen size in the intro screen
    			g.setColor(Color.gray); //the background color
    			g.fillRect(0, 0, getWidth(), getHeight()); // writing the background to white
    			g.setFont(Mono); // changing the font to the one i made called Mono
    			g.setColor(Color.black); // changing the color to black
    			g.drawString("SPACE INVADERS", 130, getHeight()/4); //writing space invaders
    			g.drawString("Computer Science 2011/12", 100, 30); // writing computer science
    			g.drawRect (0,0,5,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,10,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,15,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,20,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,25,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,30,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,35,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,40,getHeight()); // drawing a boarder 
    			g.setColor(Color.red); // changing the color to red
    			g.drawRect (0,0,6,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,11,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,16,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,21,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,26,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,31,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,36,getHeight()); // drawing a boarder 
    			g.drawRect (0,0,41,getHeight()); // drawing a boarder 
    			g.drawString("SPACE INVADERS", 132, (getHeight()/4)+2); // writing space invaders
    			g.drawString("Computer Science 2011/12", 102, 32); // writing computer science
    			g.setFont(Monosmall); // changing the font to the one i made called Monosmall
    			g.drawString("Charles - Chengcheng - Guo", 280,270); // writing charles chengcheng guo
    			g.setColor(Color.black); //changing the color to black
    			g.drawString("Charles - Chengcheng - Guo", 282,272); // writing charles chengcheng guo
    			g.drawString("Press '1' to start the game", 180, 130);
    			g.drawString("Press '2' to pause the game", 180, 150);
    			g.drawString("Press '3' to view credits", 180, 170);
    	}
    		if (state == credits){
    			g.setColor(Color.gray); //the background color
    			g.fillRect(0, 0, getWidth(), getHeight()); // writing the background to white
    			g.setFont(TimesnewRoman); // changing the font to the one i made called Times new Roman
    			g.setColor(Color.black); // changing the color used for the font to black
    			g.drawString("Game made by Charles Guo", 40, 60); // Thanking myself
    			g.drawString("Special thanks to Mr.Radulovic", 40, 100); // Thanking Mr.Radulovic
    			g.drawString("Special thanks to Ms.Mihaila", 40, 140); // Thanking Ms.Mihaila
    			g.setColor(Color.red); // changing the color used for the font to black
    			g.drawString("Game made by Charles Guo", 42, 62); // Thanking myself
    			g.drawString("Special thanks to Mr.Radulovic", 42, 102); // Thanking Mr.Radulovic
    			g.drawString("Special thanks to Ms.Mihaila", 42, 142); // Thanking Ms.Mihaila
    		}
    		if(state==WON)
    			g.drawString("YOU WIN!", getWidth()/2-30, getHeight()/2-6);
    		else if(state==LOST)
    			g.drawString("You Lose.", getWidth()/2-30, getHeight()/2-6);
    		graphics.drawImage(image, 0, 0, null);
    	}
    
    	//dt in seconds.
    	public void update(double dt){ 
    		if(state == PLAYING){ //if the game is running test the following
    			if(left) // if the user pressed and has their hand on the left button
    				player.moveLeft(dt);
    			if(right)// if the user pressed and has their hand on the right button
    				player.moveRight(dt);
    			for(int i = 0; i < badGuys.size(); i++)
    				badGuys.get(i).update(dt, bullets);
    			for(int i = 0; i < bullets.size(); i++)
    				bullets.get(i).update(dt);
    			testForBulletCollisions();
    			if(hasWon()) // if the user wins
    				state = WON; // change state to WON
    			else if(hasLost()) //if the user lost
    				state = LOST; //change state to LOST
    		}
    	}
    
    	public void testForBulletCollisions(){
    		top:for(int i = 0; i < bullets.size(); i++){
    			for(int j = 0; j < badGuys.size(); j++){
    				if(badGuys.get(j).hitBy(bullets.get(i)) && bullets.get(i).goingUp()){
    					bullets.remove(i);
    					badGuys.remove(j);
    					i--;
    					continue top;
    				}
    			}
    			if(player.hitBy(bullets.get(i)) && !bullets.get(i).goingUp()){
    				player.hit();
    				bullets.remove(i);
    				i--;
    			}
    		}
    	}
    
    	public boolean hasWon(){
    		return badGuys.size()==0;
    	}
    
    	public boolean hasLost(){
    		for(int i = 0; i < badGuys.size(); i++){
    			if(badGuys.get(i).getY()>getHeight())
    				return true;
    		}
    		if(player.getHealth()<=0)
    			return true;
    		return false;
    	}
    
    
    	
    	public void run(){
    		long time = System.nanoTime();
    		while(true){
    			try{Thread.sleep(10);}catch(Throwable t){} //waiting 10 miliseconds
    			double dt = (System.nanoTime()-time)*1E-9;
    			time = System.nanoTime();
    			update(dt);
    
    			repaint();
    		}
    	}
    
    	/*********************************************************************************/
        /***************************** Methods for listeners *****************************/
        /*********************************************************************************/
    	public void keyPressed(KeyEvent e){
    		switch(e.getKeyCode()){
    		case KeyEvent.VK_LEFT: left = true; break;
    		case KeyEvent.VK_RIGHT: right = true; break;
    		case KeyEvent.VK_1: state = PLAYING; break; 
    		case KeyEvent.VK_2: state = menu; break; 
    		case KeyEvent.VK_3: state = credits; break; 
    		}
    	}
    
    	
    	public void keyReleased(KeyEvent e){
    		switch(e.getKeyCode()){
    		case KeyEvent.VK_LEFT: left = false; break;
    		case KeyEvent.VK_RIGHT: right = false; break;
    		}
    	}
    
    	
    	public void keyTyped(KeyEvent e){
    		if(e.getKeyChar()==' ')
    			player.shoot(bullets);
    	}
    }
    Last edited by DouboC@gmail.com; 01-18-2012 at 01:41 AM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,602
    Rep Power
    23

    Default Re: Key Listener problem!

    Does the listener have the focus?

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,602
    Rep Power
    23

    Default Re: Key Listener problem!

    Cross posted at Key Listener problem!

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Key Listener problem!

    If you are seeing different behaviour then the most likely reason is that the code is different, or that you are running the code in a different way (eg applet viewer vs embedding on a webpage).

    You can check whether the key listener ever gets called by putting System.out.println("Pressed! " + e); at the start of the keyPressed() method. You might want to call isFocusOwner() somewhere. (init()? but I'm not sure when in its life cycle an applet might be expected to get focus.) If you don't see any key presses this might be because the applet does not have the focus.

Similar Threads

  1. Replies: 2
    Last Post: 12-11-2011, 10:44 PM
  2. Adding a key listener problem
    By trishtren in forum New To Java
    Replies: 3
    Last Post: 06-02-2011, 02:49 PM
  3. Problem with key listener
    By Mikelmao in forum New To Java
    Replies: 1
    Last Post: 03-14-2011, 02:02 PM
  4. Problem in action listener
    By cool in forum AWT / Swing
    Replies: 4
    Last Post: 11-16-2010, 07:44 AM
  5. #key listener problem
    By mij1_7 in forum New To Java
    Replies: 2
    Last Post: 02-14-2009, 09:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •