Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

How can i use UP and DOWN key?

Can i have any help please.. hmm is hard for me to move the ball through y axis. it seems all movements of my keys are in x axis.

heres the code for my applet:

import java.applet.*;
import java.awt.*;

public class snake extends Applet implements Runnable
{

int x_pos = 30; // x - Position des Balles
int y_pos = 30; // y - Position des Balles
int x_speed = 1;
int y_speed = 2;
int radius = 20; // Radius des Balles
int appletsize_x = 300; // Gre des Applets in x - Richtung
int appletsize_y = 300; // Gre des Applets in y - Richtung

private Image dbImage;
private Graphics dbg;

public void init()
{
setBackground (Color.blue);
}

public void start ()
{

Thread th = new Thread (this);
// Starten des Threads
th.start ();
}

public void stop()
{

}

public void destroy()
{

}

public boolean keyDown (Event e, int key)
{

if (key == Event.LEFT)
{

x_speed = -1;
}

else if (key == Event.RIGHT)
{

x_speed = 1;
}
if (key == Event.DOWN)
{

y_speed = -5;
}

else if (key == Event.UP)
{

y_speed = 5;
}

else if (key == 32)
{
x_speed = 0;
}
else
{

System.out.println ("Charakter: " + (char)key + " Integer Value: " + key);
}

return true;
}

public void run ()
{

Thread.currentThread().setPriority(Thread.MIN_PRIORITY);


while (true)
{

if (x_pos > appletsize_x - radius)
{

x_speed = -1;
}

else if (x_pos < radius)
{

x_speed = +1;
}


x_pos += x_speed;

repaint();

try
{

Thread.sleep (20);
}
catch (InterruptedException ex)
{
// do nothing
}


Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}


public void update (Graphics g)
{
// Initialisierung des DoubleBuffers
if (dbImage == null)
{
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics ();
}


dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);


dbg.setColor (getForeground());
paint (dbg);


g.drawImage (dbImage, 0, 0, this);
}

public void paint (Graphics g)
{
g.setColor (Color.red);

g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
}
}
[2895 byte] By [robmars] at [2007-11-11 10:17:32]
# 1 Re: How can i use UP and DOWN key?
Unless I overlooked something, I don't see anywhere in your code where keyDown() will ever be called.

Add a KeyListener and listen for KeyEvents.
Phaelax at 2007-11-11 22:31:43 >