views:

39

answers:

2

Here is my code, what i'm trying to do is to move that rectangle with a key press. Questions - how do i specify it on arrow keys and why it won't allow me to work it that way? It underlines

my paddle object in red in KeyPressed event and won't run.

import acm.graphics.*;
import acm.program.*;
import java.awt.event.*;
public class BreakOut extends GraphicsProgram {
/** Runs the program */
public void run() {

 GRect paddle = new GRect(200, 400, 100, 20);
 add(paddle);

 addKeyListeners();

}
public void keyPressed(KeyEvent e){
 paddle.move(5,0);


}
A: 

paddle is a local variable in the run() method. It is not accessible from the keyPressed(KeyEvent e) method.

You probably want to turn paddle into a field.

Don Roby
A: 

I have no idea what the ACM packages are about and I have no idea what the GrphaicsProgram class is so I don't really know what you are doing.

But, in general, KeyEvents are only passed to object that have have focus. I can't tell if your paddle object has focus or not.

I would suggest you can write your program using Swing and then take advantage of using Key Bindings instead of relying on KeyEvents.

camickr