Java JPanel 移动(keylistener)不工作

标签 java swing controller keylistener

I've been trying to let an image move up and down in Jpanel for quite a long while, but it never seems to work.

If I put "y = y - 1" in the view, it makes the image move up, so I guess the problem is with the keylistener, right?

Could anyone help me with this please? To be honest... I think it will be a very stupid mistake but I can't find how to get it to work.

Extra information: I am using BlueJ to from it, with 4 classes in the basic program for my question. I realize that a lot of people on the internet said to use key bindings and not KeyListener but I don't understand key bindings as for now...

--- 根据 Hovercraft Full Of Eels 的建议,我将尝试使用快捷键。 ---

因此,键绑定(bind)有 2 个“命令”可以工作:输入和操作。

复制此代码并为我的程序更改它:

protected void addBindings() {
   int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
   InputMap inputMap = getInputMap(condition); // What does this do?

   KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.KEY_PRESS);
   inputMap.put(key, move(0, 2));

移动函数:

protected void beweeg (int dx, int dy)
{
    view.x = view.x + dx;
    view.y = view.y + dy;
}

我不得不说...这个论坛上的代码系统令人难以置信的沮丧。 尝试这个时我得到:“找不到符号 - 方法 getInputMap(int)” 我需要在某处声明吗?我对此一无所知。

最佳答案

你问:

When trying this I get: "cannot find symbol - method getInputMap(int)" Did I need to declare it somewhere?

必须在派生自 JComponent 或其子项之一的对象(例如 JPanel)上调用此方法。此错误消息意味着您是在未扩展 JComponent 或其子项之一(如 JPanel)的类内部进行此调用。一种可能的解决方案是在您的 JPanel 对象上调用要将绑定(bind)附加到的对象上的方法。


说到链接,这里有一些我的:link , link , link , link , link , link ,...

关于Java JPanel 移动(keylistener)不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23444632/

相关文章:

ruby-on-rails - 测试无法直接访问的 RSpec Controller 操作

ios - PKPaymentAuthorizationViewController 总是返回 nil?

java - 使用 Java 中的 cuda 设备内核?

java - 将 JApplet 添加到 JFrame(或 AWT 框架)

java - JTree 在节点展开时扩大宽度

java - 使用 Java7 在 OSX 上启用 Swing 菜单

javascript - AngularJS - 指令包装而不丢失与 Controller 的连接

java - 禁用按钮时是否需要删除actionListener?

java - Android SQLite 查询在选择器中有问号,在 selectionArgs 中有空

java - 使用递增计数命名多个字符串