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?