#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    2
    Rep Power
    0

    Exclamation Java KeyListener Troubles.


    Hey Everyone As my Name Suggests I am a new Programmer but I am having trouble with a basic program that simply creates a white oval on a black page which you are able to move around using the WASD keys. However when I run the program the black page and white dot appears but when I try to move the oval using the WASD nothing happens. No errors occur in the console and Debug has so far been useless. I use NetBeans 7.3 as my IDE. I'm guessing it must be a problem with the KeyListener but I honestly have no idea ???? I am sorry if this Post breaks any of your rules. I am new to Forums.

    Thanks: TheNewCoder

    Here is my Code:

    package firstgame;

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;


    public class FirstGame extends JPanel implements KeyListener{

    private int x =5, y = 5;

    public FirstGame(){
    setSize(new Dimension(500, 400));
    setPreferredSize(new Dimension(500, 400));
    setFocusable(true);
    addKeyListener(this);
    }

    public void paint(Graphics g){
    g.setColor(Color.BLACK);
    g.fillRect(0,0,getWidth(),getHeight());

    g.setColor(Color.WHITE);
    g.fillOval(x, y, 20, 20);

    repaint();
    }


    public static void main(String[] args) {

    FirstGame game = new FirstGame();

    JFrame frame = new JFrame();
    frame.setTitle("Dodge the Rectangles");
    frame.setSize(new Dimension(500, 400));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.add(game);
    frame.pack();
    frame.setResizable(false);
    }

    @Override
    public void keyTyped(KeyEvent e) {
    int c = e.getKeyCode();
    if(c == KeyEvent.VK_W){
    y--;}
    if(c == KeyEvent.VK_S){
    y++;}
    if(c == KeyEvent.VK_A){
    x--;}
    if(c == KeyEvent.VK_D){
    x++;}
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
    }
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Feb 2004
    Location
    Mobile, Alabama
    Posts
    4,023
    Rep Power
    1285
    This is from the documentation.

    For key typed events, the getKeyCode method always returns VK_UNDEFINED.
    You can use getKeyChar()
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    2
    Rep Power
    0

    Thanks!


    Thanks Alot!!!

IMN logo majestic logo threadwatch logo seochat tools logo