I am back with a new question about the same code as last time. I took a lot of the suggestions that were given, and changed a few things. The program compiles, but no rectangle appears with any input. People in the last thread said that the code would work with the issues fixed, but this doesn't seem to work. I don't know if it a problem with the graphics (I think someone else suggested to do what I did in the code I have now) or with the way I am accepting key inputs.
Anyways, the program below is supposed to have a rectangle drawn, and for that rectangle be moved one coordinate to the right or left depending on if you press the <- or -> key on your keyboard. However, no rectangle appears with any input.
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;
if (loopThread == null)
{
loopThread = new Thread();
loopThread.start();
}
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)); //sets color to white
g.fillRect(50+platPos, 200, 100, 20); //draws over whatever existing rectangle there is with white
platPos--;
g.setColor(new Color(100,100,100)); //sets new color
g.fillRect(50+platPos,200, 100,20); //draws new rectangle
left = false;
}
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);
right = false;
}
}
public boolean keyDown(Event e, int key)
{
if (key == Event.LEFT)
left = true;
if (key == Event.RIGHT)
right = true;
return true;
}
}
Also I want to use applet, not JFrame. Just a personal preference. Thanks for any help! ^.^