Hello everyone
I’m currently learning java at school, so I get these program examples that I should copy and compile, to see how the code works. The problem is, that the one I’m currently working on doesn’t work, and I havent been able to figure out why. The program is an applet game that lets the user control a little blue dot, and move it around the screen using the arrow keys. The problem is that once I run the applet, the dot won’t move. Could anyone help me with this?
Source code:
import java.applet.;
import java.awt.;
import java.awt.event.*;
public class KeyApp4 extends Applet implements Runnable, KeyListener
{
// Bilens variabler
int RADIE = 20;
double bilx = 200, bily = 200;
double vx = 0, vy = 0;
// Fönsterstorleksvariabler
Dimension appletSize;
// Knapptryckningsvariabler
boolean left = false, right = false, up = false, down = false;
public void init()
{
appletSize = getSize();
addKeyListener( this);
requestFocus();
}
public void paint( Graphics g)
{
// Ritar bilen
g.setColor( Color.blue);
g.fillOval( (int) (bilx - RADIE), (int) (bily - RADIE), 2*RADIE, 2*RADIE);
}
public void start()
{
// Ny animeringstråd
Thread tråd = new Thread( this);
tråd.start();
}
public void run()
{
while( true) {
// Ändrar hastigheten beroende på användarens knapptryckningar
if( left) vx = vx - 0.05;
if( right) vx = vx + 0.05;
// Kollar så att bilen stannar när den träffar väggen
if( bilx + RADIE > appletSize.width || bilx - RADIE < 0) vx = 0;
if( bily + RADIE > appletSize.height || bily - RADIE < 0) vy = 0;
// Förflyttar bilen
bilx = bilx + vx;
bily = bily + vy;
repaint();
try { Thread.sleep( 10); } catch( InterruptedException ie) {}
}
}
public void keyTyped( KeyEvent e) {}
public void keyPressed(KeyEvent e) {
int key = e.getKeyChar();
if (key == KeyEvent.VK_LEFT) left = true;
if (key == KeyEvent.VK_RIGHT) right = true;
if (key == KeyEvent.VK_UP) up = true;
if (key == KeyEvent.VK_DOWN) down = true;
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyChar();
if (key == KeyEvent.VK_LEFT) left = false;
if (key == KeyEvent.VK_RIGHT) right = false;
if (key == KeyEvent.VK_UP) up = false;
if (key == KeyEvent.VK_DOWN) down = false;
}
}