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

Thread: Action Listeners and Key Listeners Help

  1. #1
    Junior Member
    Join Date
    Apr 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Action Listeners and Key Listeners Help

    Ok so I am making a pong game and everything works well until I added buttons to a new panel. When I have the buttons added they work but the key listeners stop working if anyone could help that would be great here is my code. Thank you very much to anyone that can help me.

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JButton;
    import java.awt.BorderLayout;
    import javax.swing.*;
    import java.util.Random;
    //import java.lang.Math;
     
    public class Ball extends JPanel implements Runnable, ActionListener, ItemListener
    {
    	private static final long serialVersionUID = 1L;
            // Positions on X and Y for the ball, player 1 and player 2
    	private Random random = new Random();
    	private int ballX = 140, ballY = 110, player1X=10, player1Y=100, player2X=275, 
    	player2Y=100, p1stripeX = 10, p1stripeY = 110, p2stripeX = 275, p2stripeY = 110, speed = 0, ballXDirection, ballYdirection, 
    	bulletX2 = 50, bulletY2 = 0, bulletX1 = 50, bulletY1 = 0;
    	private int ballYtemp;
    	private int contPlay1temp = 0, contPlay2temp = 0;
    	private int rdycont1 = 0, rdycont2 = 0;
     
    	private JPanel buttonPanel = new JPanel();
    	private JCheckBox aibutton;
    	private KeyListener listener;
     
    	Thread thread, paddles;
    	int right=5; // to the right
    	int left= -5; //to the left
    	int up=5; // upward
    	int down= -5; // down
    	int width, height, bulletW, bulletH; // Width and height of the ball and bullet
    	// Scores
    	int contPlay1=0, contPlay2=0;
    	int powerupX = 180, powerupY = 0, powercount = 0;
    	boolean powerup;
    	boolean player1Up,player1Down, player2Up, player2Down, ai = true, shoot1, shoot2, shotready1, shotready2, fired1, fired2;
    	boolean play, gameOver;
     
     
    	public Ball(){
    		play=true;
    		thread=new Thread(this);
    		thread.start();
     
    		setFocusable(true);
     
    		setLayout(new BorderLayout());
     
     
    		JButton slow = new JButton("Slow");
    		slow.addActionListener(this);
    		buttonPanel.add(slow,BorderLayout.SOUTH);
     
    		JButton normal = new JButton("Normal");
    		normal.addActionListener(this);
    		buttonPanel.add(normal,BorderLayout.SOUTH);
     
    		JButton fast = new JButton("Fast");
    		fast.addActionListener(this);
    		buttonPanel.add(fast,BorderLayout.SOUTH);
     
     
    		 aibutton = new JCheckBox("Ai?");
    		 aibutton.addItemListener(this);
    		 aibutton.setSelected(false);
     
    		 buttonPanel.add(aibutton);
     
     
    		 add(buttonPanel,BorderLayout.SOUTH);      [COLOR="Red"]<== once I added this the keys stop working.[/COLOR]
     
    	}
     
    	// Draw ball and paddles
    	public void paintComponent(Graphics gc){
    		setOpaque(false);
    		super.paintComponent(gc);
     
    		// Draw ball
    		gc.setColor(Color.blue);
    		gc.fillOval(ballX, ballY, 8,8);
     
    		// Draw board
    		gc.setColor(Color.black);
    		gc.drawRect(0, 25, 293, 200);
     
    		// Draw bullet2
    		if (fired2 == true)
    		{
    			gc.setColor(Color.red);
    		}
    		else
    		{
    			gc.setColor(Color.white);
    		}
    		gc.fillRect(bulletX2,bulletY2, 15, 5);
     
    		// Draw PowerUp
    		if (powerup == true)
    		{
    			gc.setColor(Color.cyan);
    		}
    		else
    		{
    			gc.setColor(Color.white);
    		}
    		gc.drawRect(powerupX, powerupY, 15, 15);
     
    		//Draw bullet1
    		if (fired1 == true)
    		{
    			gc.setColor(Color.red);
    		}
    		else
    		{
    			gc.setColor(Color.white);
    		}
    		gc.fillRect(bulletX1,bulletY1, 15, 5);
     
    		// Draw paddles
    		gc.setColor(Color.green);
    		gc.fillRect(player1X, player1Y, 10, 25);
    		gc.fillRect(player2X, player2Y, 10, 25);
     
    		// Draw paddles stripe
    		gc.setColor(Color.orange);
    	//	gc.fillRect(p1stripeX, p1stripeY, 10, 5);
    		gc.fillRect(p2stripeX, p2stripeY, 10, 5);
     
    		//Draw scores
    		gc.setColor(Color.black);
    		if (ai  == true)
    		{
    			gc.drawString("Computer: "+contPlay1, 10, 10);
    		}
    		else
    		{
    			gc.drawString("Player1: "+contPlay1, 25, 10);
    		}
     
    		if (shotready1 == true)
    			gc.drawString("Shot: Ready", 30, 20);
    		else
    			gc.drawString("Shot: Empty", 30, 20);
     
    		gc.drawString("Player: "+contPlay2, 180, 10);	
    		if (shotready2 == true)
    			gc.drawString("Shot: Ready", 200, 20);
    		else
    			gc.drawString("Shot: Empty", 200, 20);
    		if(gameOver)
    			gc.drawString("Game Over", 100, 125);
    	}
     
     
    	// Positions on X and Y for the ball
    	public void drawBall (int nx, int ny)
    	{
    		ballX= nx; 
    		ballY= ny; 
    		this.width=this.getWidth();
    		this.height=this.getHeight();
    		repaint();
    	}
     
    	// Position of X and Y for bullet2
    	public void drawBullet2 (int nx, int ny)
    	{
    		bulletX2 = nx;
    		bulletY2 = ny;
    		this.bulletW = this.getWidth();
    		this.bulletH = this.getHeight();
    		repaint();
    	}
    	// Position of X and Y for bullet1
    	public void drawBullet1 (int nx, int ny)
    	{
    		bulletX1 = nx;
    		bulletY1 = ny;
    		this.bulletW = this.getWidth();
    		this.bulletH = this.getHeight();
    		repaint();
    	}
     
        //  Key Pressed
    	public void keyPressed(KeyEvent evt)
        {
            switch(evt.getKeyCode())
            {
                // Move player 1
                case KeyEvent.VK_W :
                	player1Up = true;
     
                	break;
                case KeyEvent.VK_S : 
                	player1Down = true;
                	break;
                case KeyEvent.VK_D :
                	shoot1 = true;
                	break;
     
                // Move player 2
                case KeyEvent.VK_UP:
                	System.out.println("up");
                	player2Up=true;
                	break;
               case KeyEvent.VK_DOWN:
            	    player2Down=true;
                	break;
               case KeyEvent.VK_LEFT:
            	    shoot2 = true;
            	    break;
            }
        }
     
        //	Key Released
        public void keyReleased(KeyEvent evt)
        {
            switch(evt.getKeyCode())
            {
    	        // Mover Player1
    	        case KeyEvent.VK_W :
    	        	player1Up = false;
    	        	break;
    	        case KeyEvent.VK_S : 
    	        	player1Down = false;
    	        	break;
                case KeyEvent.VK_D :
                	shoot1 = false;
                	break;
     
    	        // Mover Player 2
    	        case KeyEvent.VK_UP:
    	        	player2Up=false;
    	        	break;
    	        case KeyEvent.VK_DOWN:
    	    	   player2Down=false;
    	        	break;
               case KeyEvent.VK_LEFT:
            	    shoot2 = false;
            	    break;
            }
        }
     
        // Move player 1 or AI
        public void moverPlayer1()
        {
        	if (ai == true)
        	{
    			// AI
    			ai();
        	}
        	else
        	{
    	        if (player1Up == true && player1Y >= 30)
    	        {
    	        	player1Y += down;
    	        	p1stripeY += down;
    	        }
    	        if (player1Down == true && player1Y <= (this.getHeight()-68))
    	        {
    	        	player1Y += up;
    	        	p1stripeY += up;
    	        }
    	        if (shoot1 == true && shotready1 == true)
    	        	fired1 = true;
        	}
            drawPlayer1(player1X, player1Y);
        }
     
        // Move player 2
        public void moverPlayer2()
        {
            if (player2Up == true && player2Y >= 30)
            {	
            	player2Y += down;
            	p2stripeY += down;
            }
            if (player2Down == true && player2Y <= (this.getHeight()-68))
            {
            	player2Y += up;
            	p2stripeY += up;
            }
            if (shoot2 == true && shotready2 == true)
            	fired2 = true;
            drawPlayer2(player2X, player2Y);
        }
     
        // Position on Y for the player 1
        public void drawPlayer1(int x, int y){
        	this.player1X=x;
        	this.player1Y=y;
        	repaint();
        }
        // Position on Y for the player 2   
        public void drawPlayer2(int x, int y){
        	this.player2X=x;
        	this.player2Y=y;
        	repaint();
        }
     
    	public void run() {
    		// TODO Auto-generated method stub
     
    		boolean ballXmove=false;
    		boolean ballYmove=false;
     
     
    		while(true){
     
    			if(play){
     
                // The ball move from left to right
               	if (ballXmove) 
    			{
     
    				ballX += right + speed;
    				ballXDirection = -1;
    				if (ballX >= (width - 10))
    				{
    					ballXmove= false;
    				}
    			}
    			else
    			{
     
    				ballX += left - speed;
    				ballXDirection = 1;
    				if ( ballX <= 0)
    				{
    					ballXmove =  true;
    				}
    			}
     
     
                // The ball moves from up to down
               	if (ballYmove) 
    			{
    				ballYtemp = ballY;
               		ballY += up + speed;
    				if (ballY >= (height - 49))
    					ballYmove= false;
    				if (ballYtemp < ballY){
    					ballYdirection = -1;
    					}
    				else{
    					ballYdirection = 1;
    					}
    				ballYdirection = -1;
     
    			}
    			else
    			{
    				ballYtemp = ballY;
    				ballY += down - speed;
    				if ( ballY <= 25)
    					ballYmove =  true;
    				if (ballYtemp < ballY){
    					ballYdirection = -1;
    					}
     
    				else{
    					ballYdirection = 1;
    					}
    				ballYdirection = 1;
    			}
               	drawBall(ballX, ballY);
     
               	// Shoots bullet2
               	if (fired2 == true)
               	{
               		if (shotready2 == true)
               		{
    	           		bulletX2 = player2X;
    	           		bulletY2 = player2Y + 12;
    	           		shotready2 = false;
    	           	}
               		bulletX2 -= 9;
               	}
               	drawBullet2(bulletX2,bulletY2);
     
               	// Shoots bullet1
               	if (fired1 == true)
               	{
               		if (shotready1 == true)
               		{
    	           		bulletX1 = player1X + 5;
    	           		bulletY1 = player1Y + 12;
    	           		shotready1 = false;
    	           	}
               		bulletX1 += 9;
               	}
               	drawBullet1(bulletX1,bulletY1);
                // Delay
    			try 
    			{
    				Thread.sleep(30);
    			}
    			catch(InterruptedException ex)
    			{
     
    			}
     
    			// Move player 1
    			moverPlayer1();
                // Move player 2
    			moverPlayer2();
     
    			powerupPlace();
    			if (powerup == true)
    			{
     
    			}
    			else
    			{
    				powercount ++;
    			}
                // The score of the player 1 increase
    			if (ballX >= (this.getWidth() - 10))
    			{
    				contPlay1++;
    				//Check to see if player earned bullet
    				if (rdycont1 == 0)
    				{
    					contPlay2temp = contPlay2;
    				}
    				if (contPlay2temp == contPlay2)
    				{
    					rdycont1 ++;
    					if (rdycont1 >= 2)
    					{
    						shotready1 = true;
    						rdycont1 = 0;
    					}
    				}
    				else if (contPlay2temp != contPlay2)
    				{
    					rdycont1 = 0;
    				}
    			}
     
                // The score of the player 2 increase
     
    			if ( ballX == 0)
    			{
    				contPlay2++;
    				//Check to see if player earned bullet
    				if (rdycont2 == 0)
    				{
    					contPlay1temp = contPlay1;
    				}
    				if (contPlay1temp == contPlay1)
    				{
    					rdycont2 ++;
    					if (rdycont2 >= 2)
    					{
    						shotready2 = true;
    						rdycont2 = 0;
    					}
    				}
    				else if (contPlay1temp != contPlay1)
    				{
    					rdycont2 = 0;
    				}
    			}
     
    			// Game over. Here you can change 6 to any value
                            // When the score reach to the value, the game will end
    			if(contPlay1==10 || contPlay2==10){
    				play=false;
    			    gameOver=true;
    			}
     
    			// The ball stroke with the player 1
    			if(ballX<=player1X+10 && ballY>=player1Y && ballY<=(player1Y+25))
    				ballXmove=true;
     
                // The ball stroke with the player 2
    			if(ballX>=(player2X-5) && ballY>=player2Y && ballY<=(player2Y+25))
    			{
    				ballXmove=false;
     
    			}
    			// Check if Bullet Hit Player 1
    			if (bulletX2 <= 0 || (bulletX2 <= player1X + 10 && bulletY2 >= player1Y && bulletY2 <= (player1Y + 25)))
    				{
    					if(bulletX2 <= player1X + 10 && bulletY2 >= player1Y && bulletY2 <= (player1Y + 25))
    					{
    						contPlay2 += 2;
    					}
    					fired2 = false;
    					bulletX2 = 150;
    					bulletY2 = 0;
    				}
    			// Check if Bullet Hit Player 2
    			if (bulletX1 >= 290 || (bulletX1 >= player2X - 10 && bulletY1 >= player2Y && bulletY1 <= (player2Y + 25)))
    				{
    					if(bulletX1 <= player2X + 10 && bulletY1 >= player2Y && bulletY1 <= (player2Y + 25))
    					{
    						contPlay1 += 2;
    					}
    					fired1 = false;
    					bulletX1 = 150;
    					bulletY1 = 0;
    				}
    			//Check Bullet2 with Powerup
    			if (bulletX2 <= powerupX + 15 && bulletX2 >= powerupX && bulletY2 >= powerupY && bulletY2 <= powerupY + 15)
    				{
    					powerup = false;
    					fired2 = false;
    					bulletX2 = 150;
    					bulletY2 = 0;
    					contPlay1 -= 1;
    					powerupX = 180;
    					powerupY = 0;
    				}
    			//Check Bullet1 with Powerup
    			if (bulletX1 <= powerupX + 15 && bulletX1 >= powerupX && bulletY1 >= powerupY && bulletY1 <= powerupY + 15)
    				{
    					powerup = false;
    					fired1 = false;
    					bulletX1 = 150;
    					bulletY1 = 0;
    					contPlay2 -= 1;
    					powerupX = 180;
    					powerupY = 0;
    				}
     
    			}
    		}
    	}
     
    	public void ai ()
    	{
    		if (ai == true)
    		{
    	      // ball is moving towards paddle
    	      if (ballXDirection == 1) // 1 )
    	      {
                    // If ball's position smaller than paddle's, move up
     
    	            if ((player1Y + 12) < ballY && player1Y <= (this.getHeight()-68))
    	            {
    	                  player1Y += 4.5;
    	            }
                    // If ball's position greater than padle's, move down
     
    	            else if ((player1Y + 12) > ballY && player1Y >= 30)
    	            {
    	                  player1Y -= 4.5;
    	            } 
     
    	      }
     
    	      /* If the ball is moving in opposite direction to the paddle and is no danger for computer's goal move paddle back to the middle y - position*/
    	      else if (ballXDirection == -1 )//-1)
    	      {
    	            // As long as ball's y - position and paddle's y - position are different
    	    	  if (shotready1 == true && powerup == true)
    	    	  {
    	    		  player1Y = powerupY - 7;
    	              fired1 = true;
    	    	  }
    	    	    	  // if the paddle's position is over the middle y - position
     
        	  		  if ((player1Y + 12) >= 124)
                      {
                            player1Y -= 4.5;
                      }
                      // Paddle is under the middle y - position
                      if ((player1Y + 12) <= 118)
                      {
                            player1Y += 4.5;
                      }
     
    	        } 
    		}
    		else
    		{
     
    		}
    	} 
    	public void powerupPlace()
    	{
    		int temp = 0;
    		if (powerup == false && powercount >= 300)
    		{
    			temp = random.nextInt(173);
    			temp += 60;
    			powerupX = temp;
     
    			temp = random.nextInt(170);
    			temp += 30;
    			powerupY = temp;
     
    			powerup = true;
    			powercount = 0;
    		}
    	}
     
    	public void actionPerformed(ActionEvent e)
    	{
    		String buttonString = e.getActionCommand();
     
    		if (buttonString.equals("Slow"))
    		{
    			speed = -3;
    		}
    		else if (buttonString.equals("Normal"))
    		{
    			speed = 0;
    		}
    		else if (buttonString.equals("Fast"))
    		{
    			speed = 3;
    		}
    		else if (buttonString.equals("Start"))
    		{
     
    		}
    	}
     
    	public void itemStateChanged(ItemEvent e) 
    	{
     
    	    Object source = e.getItemSelectable();
    	    if (source == aibutton) 
    	    {
    	    	if (ai == false)
    	    	{
    	    		ai = true;
    	    	}
    	    	else
    	    	{
    	    		ai = false;
    	    	}
     
    	    }
     
     
    	}
     
    }

    And the class that calls this code

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import java.awt.Color;
     
     
    public class Pong extends JFrame{
     
    	private static final long serialVersionUID = 1L; // Eclipse added this automatically
     
    	private JPanel jContentPane = null;
     
    	private Ball panel = null; // This is the panel of the game class
     
     
     
     
    	private Ball getPanel() {
    		if (panel == null) {
    			panel = new Ball(); // The panel is created & speed set
     
    		}
    		return panel;
    	}
     
    	/**
    	 * This is the default constructor
    	 */
    	public Pong() {
    		super();
    		initialize();
            // Listeners for the keyboard
            this.addKeyListener (new KeyAdapter() {
            	//Method for the key pressed
                public void keyPressed(KeyEvent evt) {
                    formKeyPressed(evt);
                }
                // Method for the key released
                public void keyReleased(KeyEvent evt) {
                    formKeyReleased(evt);
                }
            });
     
    	}
     
        //	Here i'm stating the method that will send the key pressed to the game class
    	private void formKeyPressed(KeyEvent evt)
        {
            panel.keyPressed(evt);
        }
     
        //	Here i'm stating the method that will send the key released to the game class
        private void formKeyReleased(KeyEvent evt)
        {
            panel.keyReleased(evt);
        }
     
    	/**
    	 * This method initializes this
    	 * 
    	 * @return void
    	 */
    	private void initialize() {
    		this.setResizable(false);
    		this.setBounds(new Rectangle(312, 184, 300, 290)); // Position on the desktop
    		this.setMinimumSize(new Dimension(250, 250));
    		this.setMaximumSize(new Dimension(250, 250));
    		this.setContentPane(getJContentPane());
    		this.setTitle("Pong");
    	}
     
    	/**
    	 * This method initializes jContentPane
    	 * 
    	 * @return javax.swing.JPanel
    	 */
    	private JPanel getJContentPane() {
    		if (jContentPane == null) {
    			jContentPane = new JPanel();
    			jContentPane.setLayout(new BorderLayout());
    			jContentPane.add(getPanel(), BorderLayout.CENTER);
    			jContentPane.setBackground(Color.white);
    		}
    		return jContentPane;
    	}
     
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				Pong thisClass = new Pong();
    				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				thisClass.setVisible(true);
    			}
    		});
    	}
     
     
    }


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Action Listeners and Key Listeners Help

    An object that you expect to listen to events via a key listener requires focus to receive those event...my guess is that's the problem but I don't have time right now to look fully over the code. The solution would be to request focus of the object you want to listen for key events whenever another component might gain focus (eg through an action event)

  3. The Following User Says Thank You to copeg For This Useful Post:

    MyObjective (March 15th, 2013)

  4. #3
    Junior Member
    Join Date
    Apr 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Action Listeners and Key Listeners Help

    So I have been trying to use this.requestFocus(); is that the right code I haven't been able to get it to work with that I think I am just placing it in the wrong place. When the Focus is "lost" by other buttons they are just in the panel running all the time so how and when should I use this.requestFocus(); ?

    and thank you for your help.

  5. #4
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Action Listeners and Key Listeners Help

    Resurrected another zombie on another forum too (the thread has since been locked by a moderator)
    This thread has been cross posted here:

    http://www.java-forums.org/awt-swing/27334-creating-gui-events-action-listeners.html

    Although cross posting is allowed, for everyone's benefit, please read:

    Java Programming Forums Cross Posting Rules

    The Problems With Cross Posting

    db


Similar Threads

  1. JButton with "Enter Key" keyboard action
    By chronoz13 in forum Java Swing Tutorials
    Replies: 2
    Last Post: March 14th, 2012, 06:49 AM
  2. jbutton and action event
    By mt888 in forum AWT / Java Swing
    Replies: 3
    Last Post: March 26th, 2010, 06:24 AM
  3. Problem with Action Listener
    By JonoScho in forum AWT / Java Swing
    Replies: 4
    Last Post: March 19th, 2010, 01:03 AM
  4. Need Help Action Listener....
    By vhizent23 in forum AWT / Java Swing
    Replies: 2
    Last Post: October 9th, 2009, 01:46 PM