0

I have been trying to make a JPanel move with the arrow keys. It has not been working. I believe it is my inner class that extends the KeyAdapter. I'm also not sure about the ActionListener implemented were it is. The other class I have made does not matter since it is just the frame.

package jerryWorlds;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Jerry extends JPanel implements ActionListener{

int SizeX, SizeY, PosX, PosY, VelX, VelY;
Image img;
Timer time = new Timer(1, this);

public Jerry(){
    ImageIcon i = new ImageIcon();
    addKeyListener(new AL());
    time.start();
    img = i.getImage();
    PosX = 375;
    PosY = 250;
}

public void paint(Graphics g){
    Graphics2D g2d = (Graphics2D)g;
    g2d.fillRect(PosX, PosY, 50, 100);
}
public void actionPerformed(ActionEvent e) {
    PosX = PosX + VelX;
    repaint();
}

private class AL extends KeyAdapter{
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        System.out.println("YAY!");
        if(key == KeyEvent.VK_LEFT)
            VelX = -1;
        else if(key == KeyEvent.VK_RIGHT)
            VelX = 1;
    }

    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();
        if(key == KeyEvent.VK_LEFT)
            VelX = 0;
        else if(key == KeyEvent.VK_RIGHT)
            VelX = 0;
    }
}

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
kubuto2
  • 9
  • 1
  • 3
  • 2
    This post by @camickr, regarding [Motion Using the Keyboard](http://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/), will definitely add something to your knowledge :-). Seems like your question is not written in the write sense, looking at the code it appears you wanted to draw a new rectangle as you press arrow keys, you really not moving your `JPanel` as stated in your title... – nIcE cOw Jun 22 '13 at 01:30

1 Answers1

5
  • You will want to search this site for similar questions, as they usually have the same issue and same answer.
  • They will tell you that focus is one problem since a component's KeyListener won't work unless it has focus.
  • They will tell you that regardless you shouldn't use KeyListener at all but rather Key Bindings.
  • They will tell you not to override paint(...) but rather paintComponent(...) unless you are sure that you want to override painting of a component's borders and children (you don't).
  • They will tell you to be sure to call the super method inside of paintComponent(...).

Also please have a look at this animation and key bindings example.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373