[英]Java keylistener and action on object, what's wrong?
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. 我的Paddle对象在KeyPressed事件中显示为红色,并且不会运行。
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);
}
try this: 尝试这个:
import acm.graphics.*;
import acm.program.*;
import java.awt.event.*;
public class BreakOut extends GraphicsProgram {
GRect paddle;
public void run() {
paddle = new GRect(200, 400, 100, 20);
add(paddle);
addKeyListeners();
}
public void keyPressed(KeyEvent e){
paddle.move(5,0);
}
}
paddle is a local variable in the run()
method. paddle是
run()
方法中的局部变量。 It is not accessible from the keyPressed(KeyEvent e)
method. 无法从
keyPressed(KeyEvent e)
方法访问它。
You probably want to turn paddle into a field. 您可能想将桨变成一个字段。
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. 我不知道ACM包是什么,也不知道GrphaicsProgram类是什么,所以我真的不知道您在做什么。
But, in general, KeyEvents are only passed to object that have have focus. 但是,通常,KeyEvent仅传递给具有焦点的对象。 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. 我建议您可以使用Swing编写程序,然后利用键绑定而不是依赖KeyEvents。
There are two problems that I can see as of now: 到目前为止,我可以看到两个问题:
Your program has unbalanced curly braces right now, so you should probably add one to the end of your keyPressed method. 您的程序现在带有不平衡的花括号,因此您可能应该在keyPressed方法的末尾添加一个。
You're not updating the rectangle, so you'll need a loop of some kind. 您没有更新矩形,因此需要某种循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.