Drew Wood
Drew Wood

Reputation: 91

keyListener not detecting keypresses

I want to move a circle graphic around a JFrame box and decided to add a KeyListener but I can't seem to get it to work.

package keyBoardInput;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class window extends JFrame implements KeyListener {

    Rectangle rect;

    //KeyListener keyListener;

    public void init() {

        this.addKeyListener(this);

        setFocusTraversalKeysEnabled(true);
        requestFocus(true);

        rect = new Rectangle(0,0,100,100);
    }

    public window() {

        super("Title bar");
        setSize(800,600);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        setFocusTraversalKeysEnabled(true);
        requestFocus(true);
        setFocusable(true);
        //addKeyListener(keyListener);
    }

    public void paint(Graphics g){

        Graphics2D g2 = (Graphics2D)g;

        g2.setColor(Color.cyan);
        g2.fillRect(0,0,800,600);
        g2.setColor(Color.orange);
        g2.fillOval(0,0,100,100);
    }

    public void keyPressed(KeyEvent e) {

        System.out.println("test");
        int key = e.getKeyCode();

        if (key == KeyEvent.VK_W) {
            rect.setLocation(rect.x + 0, rect.y + 10);
        }
        if (key == KeyEvent.VK_S) {
            rect.setLocation(rect.x - 0, rect.y - 10);
        }
        if (key == KeyEvent.VK_A) {
            rect.setLocation(rect.x - 10, rect.y + 0);
        }
        if (key == KeyEvent.VK_D) {
        rect.setLocation(rect.x + 10, rect.y + 0);
        }

        repaint();
    }

    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}

}

Upvotes: 0

Views: 642

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

If you search here for similar questions, the answer almost always is:

  • KeyListeners only work if the listened-to component has the focus.
  • And the component must be focusable.

But there's more...

  • You should not draw in a JFrame
  • Instead draw in a JPanel or JComponent
  • And extend the paintComponent method
  • And call the super method
  • and search here for similar questions for more on this
  • and check the tutorials on drawing ..
  • Next you'll want to use key bindings instead of KeyListeners. Again, this has been well discussed on this site, but KeyListeners are very low-level listeners. You're almost always better off using higher-level constructs such as Key Bindings. Bindings are the way that Swing components listen for key strokes. They also are much more flexible when it comes to component focus.

Upvotes: 4

Related Questions