I am attaching my complete code. I am not able to get why doesn't my KeyListener work. None of the KeyListener events are fires on pressing the keyboard. Please have a look and tell me the flaws in my code
package swing; //First Class (separated class)
import javax.swing.JFrame;
public class Game extends JFrame
{
public Game()
{
setSize(800,800);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Graphic graph = new Graphic();
add(graph);
}
}
////////////////////////////////////////////
import java.awt.Color; //Second Class (separated class)
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Graphic extends JPanel implements KeyListener
{
int n1=250,n2=250,b1=5,b2=5;
public void Graphic()
{
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(true);
}
@Override
public void paint(Graphics g)
{
super.paint(g);
this.setBackground(Color.black);
g.setColor(new Color(100,180,150));
g.fillRect(n1, n2, 25, 25);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_UP)
{
n2-=5;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
///////////////////////////////////////////////
public class Swing
{ //Main Method
public static void main(String[] args)
{
new Game();
}
}