0

Basically, I am trying to make a program that moves a "platter" one pixel to the left when the left arrow key is pressed, and one to the right when the right arrow key is pressed. Currently, nothing is drawing on my output window when I compile and run, and I am not too sure what I am doing wrong here or where exactly the code isn't doing what I want. Any help is appreciated, thank you!

import java.awt.*;
import java.net.*;
import java.util.*;
import java.applet.Applet;


public class game extends Applet
{
    Thread loopThread;
    boolean left  = false;
    boolean right = false;
    int platPos = 50;

    public void run() 
    { 
        Graphics g = null;

        int i, j;
        long startTime;



        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        startTime = System.currentTimeMillis();

        while (Thread.currentThread() == loopThread) 
        {
            updatePlatter(g);
        }
    }


     public void updatePlatter(Graphics g) 
    {

         if(left)
         {
             g.setColor(new Color(255,255,255));
             g.fillRect(50+platPos, 200, 100, 20);
             platPos--;
             g.setColor(new Color(100,100,100));
             g.fillRect(50+platPos,200, 100,20);
         }

         if(right)
         {
             g.setColor(new Color(255,255,255));
             g.fillRect(50+platPos,200,100,20);
             platPos++;
             g.setColor(new Color(100,100,100));
             g.fillRect(50+platPos,200,100,20);
         }

    }

    public boolean keyDown(Event e, int key) 
    {
      if (key == Event.LEFT)
        left = true;

      if (key == Event.RIGHT)
        right = true;
      return true;
    }
}
Socks
  • 5
  • 1
  • 1
    `loopThread` is never set – jhamon May 24 '18 at 12:38
  • That and you'll probably have problems in the future as you never reset `left` and `right` back to false. – N.K May 24 '18 at 12:39
  • 1
    Sidenote: Consider looking into other options than Applets. You seem to be comparably new so this is the perfect opportunity to switch to something that is not in general considered dead. – Ben May 24 '18 at 12:45
  • Possible duplicate of [Rectangle is not moving with arrow keys](https://stackoverflow.com/questions/49863346/rectangle-is-not-moving-with-arrow-keys) – AJNeufeld May 24 '18 at 13:19

1 Answers1

0

I deleted my answer as it's impossible to fix your existing code without rewriting everything, here is a good starting point for you to learn :

http://www.cs.stir.ac.uk/~sbj/examples/Java-examples-basic/Move/Move.java

Basically it does what you want but using buttons.

Also as @Ben stated, you should consider using something else than Applet, it's pretty dead..

rilent
  • 659
  • 1
  • 6
  • 22
  • The code seems not to compile when I add this, saying the constructor for Thread(game) is not suitable – Socks May 24 '18 at 12:46