0

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) {}

}
Alice
  • 588
  • 1
  • 8
  • 25
Drew Wood
  • 91
  • 1
  • 10
  • 1
    `Ive watched plenty of tutorials, and read plenty of articles,` - Really? Virtually every answer you find in the forum will tell you NOT to use a KeyListener and USE Key Bindings. Just look under the `"Related"` heading found on the right side of this page for a few example postings on this topic. – camickr Dec 01 '13 at 04:29

1 Answers1

4

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.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • and naming conventions are important and should be used, Capitalize Class Names like `Window` (not `window`) – nexus_2006 Dec 01 '13 at 03:19
  • 1
    There's got to be a better reason for KeyBindings that just because they're of a "higher" level than KeyListeners – MultiplyByZer0 Dec 01 '13 at 03:20
  • Thank you for your response. I have truly searched the site, thats where i got the whole setFocusable and setFocusTraversalKeysEnabled(true); , and still nothing. As i said, im not to this whole jframe thing, just trying something new. Is there any lines of code to add or take out that would make this specific program work. Im trying to stay on route with some of the tutorials ive watched, not get into keyBindings. Thanks. – Drew Wood Dec 01 '13 at 03:24
  • @DrewWood: go to the swing tutorials here: [Using Swing Components](http://docs.oracle.com/javase/tutorial/uiswing/components/index.html). – Hovercraft Full Of Eels Dec 01 '13 at 03:29
  • I just looked into the Using Swing Components, and i couldn't find anything related to my problem. I dont think the problem has anything to do with the JFrame, but i can be completely wrong. – Drew Wood Dec 01 '13 at 03:36
  • @DrewWood: see [this example](http://stackoverflow.com/a/8961998), and a bunch of the answers to [this question](http://stackoverflow.com/questions/6887296/how-to-make-an-image-move-while-listening-to-a-keypress-in-java). – Hovercraft Full Of Eels Dec 01 '13 at 03:39
  • 1
    @MistressDavid How about the fact that they provide better control over focus level and they provide a re-usable API in the form of the `Action`s API, which can be used with buttons and menus... – MadProgrammer Dec 01 '13 at 04:15
  • Thanks guys for all the help. Ive changed my code a lot, based off @ Hovercraft Full Of Eels example. I simply needed to have the keyPressed methods in the constructer. Heres the code, working almost flawlessly, apart from the not being able to hold down the WASD, but the whole ke detecting part works. OOPS: Guess i cant answer the question for 8 hours, ill post the code once i can, thanks. – Drew Wood Dec 01 '13 at 04:27
  • 2
    @DrewWood, `Im trying to stay on route with some of the tutorials ive watched, not get into keyBindings` - learn how to use a better approach and don't base your code off of old tutorials that were designed for AWT, not Swing. Swing has far more powerful features. We get tired of answering the same question over and over because people don't learn the new techniques. – camickr Dec 01 '13 at 04:32