Skip to main content
GameDev.net gamedev.net
🔒 Locked 🎮 Unity

[java] KeyListener Problem

Started by Swattkidd Sep 25, 2006 at 7:58 PM 2 replies 500+ views
Original Post
Swattkidd
Swattkidd
Ok im trying to get the rectangle to move down when the down key is pushed, ive done this before, with an ActionListener also but its not working now which must mean i have a simple little error somewhere that i cannot catch, help is appreciate thanks!
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class CKS extends Applet implements Runnable, KeyListener
{
    
    int y=0;
             
    Thread th;
    public void init()
    {
        
        setBackground(Color.blue);
        th = new Thread(this);
        th.start();
    }
        public void run()
        {
            while(true)
            {
                
                repaint();
            
            try{
               th.sleep(1000/300);
            }
                catch(InterruptedException e)
                {
                }
            }
        }
        public void paint(Graphics g)
        {
           
           g.drawRect(0,y,10,20);
           
        }
        public void keyPressed(KeyEvent evt)
        {
            int key = evt.getKeyCode();
            
            if(key == KeyEvent.VK_DOWN)
            {
                y++;
                repaint();
            }
            
        }
        public void keyReleased(KeyEvent evt)
        {         
        }
        public void keyTyped(KeyEvent evt)
        {            
        }
      
        }
Son of Cain
Son of Cain
Quote:
Original post by OrangyTang
It's been a while since I did any applet stuff, but don't you have to attach your key listener to the display during the init() method?


Sure, you have to add the listener to the applet, otherwise it won't catch up any events.
a.k.a javabeats at yahoo.ca
Swattkidd
Swattkidd
Thanks for the help

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.