Reputation: 129
so I've been trying to do some simple coding: Moving a blue square with the WASD keys,
public static void main (String args[])
{
new MoveWASD();
}
public MoveWASD()
{
super("Use-WASD-to-Move");
setSize(800, 450);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
g.setColor(Color.WHITE);
g.fillRect(0, 0, 800, 450);
g.setColor(Color.BLUE);
g.fillRect(Location[0], Location[1], 20, 20);
System.out.println("PRINTEDs");
}
public class MoveDetection extends Thread implements KeyListener
{
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent arg0)
{
public void run()
{
while(true)
{
try
{
if(event.getKeyChar() == 'w')
{
Location[1] = Location[1] - 20;
Repeat = true;
}
else if(event.getKeyChar() == 'd')
{
Location[0] = Location[0] + 20;
}
else if(event.getKeyChar() == 's')
{
Location[1] = Location[1] + 20;
}
else if (event.getKeyChar() == 'a')
{
Location[0] = Location[0] - 20;
}
else
{
Location[0] = Location[0];
}
Thread.sleep(75);
}
catch(Exception e)
{
break;
}
}
}
}
}
However, a get an error when putting to static voids one into the other, the arrow (up above) points to my two errors: one under run which says: Syntax error on token "void", @ expected and another under the end parenthasis in run() which says: Syntax error, insert "EnumBody" to complete BlockStatements Also, when I put a "System.out.write() under any "void" under my movedetection class it does not display, which probably means it isn't getting to it... As I have just begun coding, I have no idea what this means, any help?
Upvotes: 0
Views: 55
Reputation: 424993
You have declared a method in a method:
public void keyPressed(KeyEvent arg0) {
public void run() {
while(true) {
...
You can't do that. Try removing the public void run()
public void keyPressed(KeyEvent arg0) {
while(true) {
...
Or if you're trying to start a thread (which I suspect you are):
public void keyPressed(KeyEvent arg0) {
new Thread(new Runnable() {
public void run() {
while(true) {
...
}
}
}).start();
}
Upvotes: 0
Reputation: 61138
In Java you cannot nest methods in other methods, maybe read this.
You need to call the method from the other method
public void run(KeyEvent event) {
//do stuff
}
public void keyPressed(KeyEvent event) {
run(event);
}
Perhaps more importantly you have a while(true)
in an event handler. This will cause the EDT to be blocked causing the GUI to freeze.
I don't see any reason for the while
loop. The key pressed event will be fired on each key press.
Upvotes: 1