Results 1 to 7 of 7
  1. #1
    rajkobie is offline Member
    Join Date
    Nov 2010
    Posts
    54
    Rep Power
    0

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

  2. #2
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    393
    Rep Power
    4

    Default

    Please put the code in [ CODE][ /CODE] tags (without the space) to make it more readable.

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,891
    Rep Power
    25

    Default

    Also you left off the import statements. Please add them. Can't compile and test without them.

  4. #4
    rajkobie is offline Member
    Join Date
    Nov 2010
    Posts
    54
    Rep Power
    0

    Default

    Java Code:
    import javax.swing.JFrame;
    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 );
    }
    }
    
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    
    import javax.swing.JPanel;
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import java.awt.Toolkit;
    import java.awt.image.BufferStrategy;
    import java.awt.Canvas;
    import java.awt.Color;
    
    import java.awt.Frame;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Timer;
    import java.util.TimerTask;
    
    import javax.swing.*;
    import sun.audio.*;
    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 )
        {
        } 
     }
    }
    Please help me

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    1. Use a javax.swing.Timer, not java.util.Timer. The Swing Timer is designed to be used in conjunction with Swing GUIs.
    How to Use Swing Timers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

    2. Never never call sleep(...) on the EDT. What are you trying to achieve by calling sleep(...) in painting code anyways?

    3. Load images using ImageIO#read(...). It's pointless to construct an ImageIcon only to retrieve its image.

    As to your primary question, a JPanel isn't focusable by default, and key events only go to the focused component. You can setFocusable(true) or (much better) achieve the desired results with key bindings.
    How to Use Key Bindings (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)

    db

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,891
    Rep Power
    25

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

Similar Threads

  1. Multiple keyboard presses
    By abbeywell in forum Java Gaming
    Replies: 6
    Last Post: 05-02-2011, 05:57 PM
  2. Why isnt this working?
    By GoingThroAPhase in forum New To Java
    Replies: 4
    Last Post: 04-03-2010, 03:36 AM
  3. Replies: 11
    Last Post: 12-25-2009, 11:30 PM
  4. why isnt it sending value
    By snitdesne in forum New To Java
    Replies: 5
    Last Post: 10-24-2008, 08:24 PM
  5. Responding to button presses
    By Java Tip in forum javax.swing
    Replies: 0
    Last Post: 06-26-2008, 08:38 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
  •