#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2010
    Posts
    66
    Rep Power
    4

    Why isnt my program detecting any key presses?


    public class Tester
    {
    // instance variables - replace the example below with your own
    public static void main ( String [ ] args )
    {
    JFrame myFrame;
    MainBoard myMainSwitchBoard = new MainBoard ( );
    myFrame = new JFrame ( "BomberMan" );
    myFrame.getContentPane( ).add ( myMainSwitchBoard );

    myFrame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
    myFrame.setSize ( 1000, 735);
    myFrame.setResizable ( false );
    myFrame.setVisible ( true );
    }
    }

    public class MainBoard extends JPanel
    {
    // instance variables - replace the example below with your own
    private Image myBackground;
    private Image myRight;
    private Image myLeft;
    private Timer myTimer;
    private int intMyRandom;
    /**
    * Constructor for objects of class MainBoard
    */
    public MainBoard()
    {
    // initialise instance variables
    myBackground = new ImageIcon ( "Background.jpg" ).getImage( );
    myRight = new ImageIcon ( "Right.jpg" ).getImage( );
    myLeft = new ImageIcon ( "Left.jpg" ).getImage( );
    myTimer = new Timer ( true );

    myTimer.scheduleAtFixedRate( new TimerTask( )
    {
    public void run()
    {
    repaint( );
    }//Ends the run method
    }, 0, 100);

    addKeyListener ( new KeyAdapter ( )
    {
    /**
    * This method is going detect any key pressed evenets
    *
    * @pre: none
    * @param: e
    * @return: none
    * @post: Does particular tasks according to key stroke
    */
    public void keyPressed ( KeyEvent e )
    {
    //Gets the movements from the MoveBomber class
    int k = e.getKeyCode( );

    if ( k == KeyEvent.VK_LEFT )
    {
    System.out.println ( "Left" );
    }
    }//Ends the keyPressed method

    /**
    * This method is going detect any key released evenets
    *
    * @pre: none
    * @param: e
    * @return: none
    * @post: Does particular tasks according to key release
    */
    public void keyReleased ( KeyEvent e )
    {
    //Gets the released movements from MoveBomber class

    }//Ends the keyReleased method
    }//Ends the addKeyListener method which adds the KeyListener movements
    );
    }

    /**
    * An example of a method - replace this comment with your own
    *
    * @param y a sample parameter for a method
    * @return the sum of x and y
    */
    public void paintComponent (Graphics g )
    {
    // put your code here
    Graphics2D grGraphics = (Graphics2D ) g;
    grGraphics.drawImage ( myBackground ,0 ,0 ,null );
    drawImage( g );
    }

    public void drawImage ( Graphics g )
    {
    intMyRandom = 0 + (int)(Math.random() * ((1) + 1));
    Graphics2D grGraphics = (Graphics2D ) g;
    if ( intMyRandom == 0 )
    {
    grGraphics.drawImage ( myRight ,500 ,367 ,null );
    }
    else if ( intMyRandom == 1 )
    {
    grGraphics.drawImage ( myLeft ,500 ,367 ,null );
    }

    try
    {
    Thread.sleep ( 60 );
    }
    catch ( Exception ex )
    {
    }
    }
    }
    I am kind of confused why it isnt catching any key presses. Can someone help me out?
    Last edited by rajkobie; May 18th, 2011 at 11:41 PM.
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,696
    Rep Power
    347
    See posts on the other forum:
    http://www.java-forums.org/new-java/44293-why-isnt-my-program-detecting-any-key-presses.html#post209488
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2011
    Posts
    21
    Rep Power
    0
    The primary reason why it didn't work is because your keyListener was in your MainBoard class and didn't have focus, I put it in the Main class and it works great. Have fun with your project... Here is the working code for the Main class, you will have to adjust the package names:

    Code:
    package javaapplication66;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.JFrame;
    public class Main
    {
        // instance variables - replace the example below with your own
        public static void main(String[] args)
        {
            JFrame myFrame;
            MainBoard myMainSwitchBoard = new MainBoard();
            myFrame = new JFrame("BomberMan");
            myFrame.getContentPane().add(myMainSwitchBoard);
    
            myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myFrame.setSize(1000, 735);
            myFrame.setResizable(false);
            myFrame.setVisible(true);
    
            myFrame.addKeyListener(new KeyAdapter()
            {
    
                /**
                * This method is going detect any key pressed events
                *
                * @pre: none
                * @param: e
                * @return: none
                * @post: Does particular tasks according to key stroke
                */
                @Override
                public void keyPressed(KeyEvent e)
                {
                    System.out.println("Keypress detected: " + e.toString());
                    //Gets the movements from the MoveBomber class
                    int k = e.getKeyCode();
                    if (k == KeyEvent.VK_LEFT)
                    {
                        System.out.println("Left");
                    }
                }//Ends the keyPressed method
    
                /**
                * This method is going detect any key released events
                *
                * @pre: none
                * @param: e
                * @return: none
                * @post: Does particular tasks according to key release
                */
                @Override
                public void keyReleased(KeyEvent e)
                {
                    //Gets the released movements from MoveBomber class
    
                }//Ends the keyReleased method
            });//Ends the addKeyListener method which adds the KeyListener movements
            System.out.println("Key Listener activated");
    
        }
    }

    and here is the working code for your MainBoard class, again adjust the package name to fit your application:

    Code:
    package javaapplication66;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.util.Timer;
    import java.util.TimerTask;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    public class MainBoard extends JPanel
    {
        // instance variables - replace the example below with your own
        private Image myBackground;
        private Image myRight;
        private Image myLeft;
        private Timer myTimer;
        private int intMyRandom;
        /**
        * Constructor for objects of class MainBoard
        */
        public MainBoard()
        {
            // initialise instance variables
            myBackground = new ImageIcon("Background.jpg").getImage();
            myRight = new ImageIcon("Right.jpg").getImage();
            myLeft = new ImageIcon("Left.jpg").getImage();
            myTimer = new Timer(true);
    
            myTimer.scheduleAtFixedRate(new TimerTask()
            {
                public void run()
                {
                    repaint();
                }//Ends the run method
            }, 0, 100);
        }
    
        /**
        * An example of a method - replace this comment with your own
        *
        * @param y a sample parameter for a method
        * @return the sum of x and y
        */
        @Override
        public void paintComponent(Graphics g)
        {
            // put your code here
            Graphics2D grGraphics = (Graphics2D) g;
            grGraphics.drawImage(myBackground,0,0,null);
            drawImage(g);
        }
    
        public void drawImage(Graphics g)
        {
            intMyRandom = 0 + (int)(Math.random() * ((1)+1));
            Graphics2D grGraphics = (Graphics2D) g;
            if (intMyRandom == 0)
            {
                grGraphics.drawImage(myRight,500,367,null);
            }
            else if (intMyRandom == 1)
            {
                grGraphics.drawImage(myLeft,500,367,null);
            }
            try
            {
                Thread.sleep(60);
            }
            catch (Exception ex)
            {
                System.out.println("Error: " + ex.toString());
            }
        }
    }
    P.S. - in this forum, wrap your code with the code tags and it is easier for the programmers here to look at and diagnose your code because you won't lose the formatting. Yes, I had to reformat your code because of that, WAAAAHHH..... ... you may not like the way I formatted it - so sue me, I'm anal that way ...Oh, and I left some diagnostic System.out.println's in there, too.

IMN logo majestic logo threadwatch logo seochat tools logo