+ Reply to Thread
Results 1 to 2 of 2

Thread: Ball Game

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    13

    Ball Game

    I am creating a simple Ball game , so when user press the right or left key the ball goes to the keyboard key direction .
    I wrote that code :
    Code:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class KeyboardGame extends Applet implements KeyListener
    {
    
        private static final long serialVersionUID = 1L;
        private static boolean keyboadrRightPressed = false;
    
        public void init()
        {
             addKeyListener(this);
        }
    
        public void keyPressed(KeyEvent e) 
        {
            int keyCode = e.getKeyCode();
            if(keyCode == KeyEvent.VK_RIGHT)
            {
                keyboadrRightPressed = true;
            }
            else
            {
                keyboadrRightPressed = false;
            }
        }
    
        public void paint(Graphics g)
        {
            g.fillOval(20,20,20,20);
            g.drawString("String :"+keyboadrRightPressed,20,30);
        }
    
    }
    But it does not do anything .

  2. #2
    Your action listener might actually be working fine, but you need to repaint the applet when the key is pressed so that your string actually appears. Try changing the keyPressed to this:
    Code:
    public void keyPressed(KeyEvent e) 
    {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_RIGHT)
        {
            keyboadrRightPressed = true;
        }
        else
        {
            keyboadrRightPressed = false;
        }
        paint(); // repaint
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts