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();

    }

}

Keyboard handling in Swing is always a challenge because the focus is often not where you think. You can often get round that by creating a keyboard handler and adding that to all the components where it could possibly make sense.

The "right" solution according to Oracle is not to use the low-level event handlers at all, but to use keybindings. See https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.