Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Key Listener problem!

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    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
    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

    //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; January 17th, 2012 at 06:41 PM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,230
    Thanks
    52
    Thanked 2,296 Times in 2,267 Posts

    Default Re: Key Listener problem!

    Cross posted at Key Listener problem!

Similar Threads

  1. Action Listener?user input problem
    By gpelefty90 in forum AWT / Java Swing
    Replies: 1
    Last Post: November 2nd, 2011, 05:17 AM
  2. Problem with JText Fields and using action listener
    By toble in forum AWT / Java Swing
    Replies: 2
    Last Post: October 27th, 2010, 04:44 PM
  3. converter program, problem with action listener
    By robertson.basil in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 2nd, 2010, 05:44 AM
  4. Problem with Action Listener
    By JonoScho in forum AWT / Java Swing
    Replies: 4
    Last Post: March 19th, 2010, 01:03 AM
  5. Key listener help
    By airsim15 in forum AWT / Java Swing
    Replies: 2
    Last Post: December 13th, 2009, 02:15 PM