当前位置: 首页 > 知识库问答 >
问题:

如何在java中创建一个可用的keyrelease方法

越飞鸾
2023-03-14
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyManager implements KeyListener {
private boolean[] keys;

public KeyManager() {
    keys = new boolean[256];

}

@Override
public void keyPressed(KeyEvent e) {
    keys[e.getKeyCode()] = true;

}

@Override
public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;

}

@Override
public void keyTyped(KeyEvent e) {

}

public boolean KeyPressed(int keycode) {
    return keys[keycode];

}

public boolean KeyReleased(int keycode) {
   return keys[keycode];
 }
}

在正方形应该移动的地方初始化。KeyListener继承自GameAssistant(JFrame是用KeyListener创建的)

package TestCode;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;

import javaGD.GameAssistant.GameAssistant;

public class Game extends GameAssistant {
public int x, xSpeed, y, ySpeed;

public Game(String title, int width, int height, boolean makeResizable) {
    super(title, width, height, makeResizable);

}

@Override
public void setup() {
    x = 0;
    y = 0;
    xSpeed = 5;
    ySpeed = 5;
}

@Override
public void update() {
    if (this.Keyboard().KeyReleased(KeyEvent.VK_D)) {
        x += xSpeed;
    }

    if (this.Keyboard().KeyReleased(KeyEvent.VK_A)) {
        x -= xSpeed;
    }

    if (this.Keyboard().KeyReleased(KeyEvent.VK_W)) {
        y -= ySpeed;
    }

    if (this.Keyboard().KeyReleased(KeyEvent.VK_S)) {
        y += ySpeed;
    }
}

@Override
public void draw(Graphics g) {

    g.setColor(Color.BLACK);
    g.fillRect(x, y, 20, 20);

}

}

共有1个答案

訾高明
2023-03-14

keyreleased应该返回!keys[keycode]否则,当释放时返回false,而当按下时返回true

public boolean KeyReleased(int keycode) {
   return !keys[keycode];
}

我还建议使用密钥绑定API,而不是KeyListener,因为它更可靠,更可重用。

如果您只计划有限数量的输入操作,我将使用setenum,这样可以将“how”与“what”分离。

public enum GameInput {
    UP, DOWN, LEFT, RIGHT;
}

public class KeyManager implements KeyListener {

    private Set<GameInput> inputs = new HashSet<>();

    public KeyManager() {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // Check the key code, verify if it's one of the configured
        // actions keys
        // The key code could come from a configuration file which might
        // be customisable by the user...
        if (e.getKeyCode() == KeyEvent.VK_W) {
            inputs.add(GameInput.UP);
        } else if (e.getKeyCode() == KeyEvent.VK_S) {
            // etc...
        } // etc...
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_W) {
            inputs.remove(GameInput.UP);
        } else if (e.getKeyCode() == KeyEvent.VK_S) {
            // etc...
        } // etc...
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    public boolean isKeyPressed(GameInput input) {
        return inputs.contains(input);

    }

    public boolean isKeyReleased(GameInput input) {
        return !isKeyPressed(input);
    }
}
@Override
public void update() {
    if (this.Keyboard().isKeyReleased(GameInput.RIGHT)) {
        x += xSpeed;
    }

    if (this.Keyboard().isKeyReleased(GameInput.LEFT)) {
        x -= xSpeed;
    }

    if (this.Keyboard().isKeyReleased(GameInput.UP)) {
        y -= ySpeed;
    }

    if (this.Keyboard().isKeyReleased(GameInput.DOWN)) {
        y += ySpeed;
    }
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Box box = new Box();

        public TestPane() {
            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), "Up.pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), "Up.released");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), "Down.pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), "Down.released");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), "Left.pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), "Left.released");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "Right.pressed");
            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), "Right.released");

            am.put("Up.pressed", new KeyAction(InputAction.UP, true));
            am.put("Up.released", new KeyAction(InputAction.UP, false));
            am.put("Down.pressed", new KeyAction(InputAction.DOWN, true));
            am.put("Down.released", new KeyAction(InputAction.DOWN, false));
            am.put("Left.pressed", new KeyAction(InputAction.LEFT, true));
            am.put("Left.released", new KeyAction(InputAction.LEFT, false));
            am.put("Right.pressed", new KeyAction(InputAction.RIGHT, true));
            am.put("Right.released", new KeyAction(InputAction.RIGHT, false));

            Timer timer = new Timer(5, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    box.update(getBounds());
                    repaint();
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            box.draw(g);
        }

    }

    public class Box {

        public int x, xSpeed, y, ySpeed, width, height;

        public Box() {
            x = 0;
            y = 0;
            xSpeed = 1;
            ySpeed = 1;
            width = 10;
            height = 10;
        }

        public void update(Rectangle bounds) {
            if (!InputManager.INSTANCE.isSet(InputAction.LEFT)) {
                x -= xSpeed;
            }
            if (!InputManager.INSTANCE.isSet(InputAction.RIGHT)) {
                x += xSpeed;
            }
            if (InputManager.INSTANCE.isSet(InputAction.UP) && InputManager.INSTANCE.isSet(InputAction.DOWN)) {
                //
            } else if (!InputManager.INSTANCE.isSet(InputAction.UP)) {
                y -= ySpeed;
            } else if (!InputManager.INSTANCE.isSet(InputAction.DOWN)) {
                y += ySpeed;
            }

            if (x < bounds.x) {
                x = 0;
            } else if (x + width > (bounds.x + bounds.width)) {
                x = bounds.x + (bounds.width - width);
            }
            if (y < bounds.y) {
                y = 0;
            } else if (y + height > (bounds.y + bounds.height)) {
                y = bounds.y + (bounds.height - height);
            }
        }

        public void draw(Graphics g) {
            g.setColor(Color.BLACK);
            g.fillRect(x, y, width, height);
        }
    }

    public enum InputAction {
        UP, DOWN, LEFT, RIGHT;
    }

    public enum InputManager {
        INSTANCE;

        private Set<InputAction> actions = new HashSet<>();

        public void set(InputAction action) {
            actions.add(action);
        }

        public void remove(InputAction action) {
            actions.remove(action);
        }

        public boolean isSet(InputAction action) {
            return actions.contains(action);
        }
    }

    public class KeyAction extends AbstractAction {

        private InputAction action;
        private boolean apply;

        public KeyAction(InputAction action, boolean apply) {
            this.action = action;
            this.apply = apply;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("!");
            if (apply) {
                System.out.println("Apply " + action);
                InputManager.INSTANCE.set(action);
            } else {
                System.out.println("Remove " + action);
                InputManager.INSTANCE.remove(action);
            }
        }
    }
}

当使用KeyListener时,如果我按下(并按住)两个按钮,我可以看到“按下”操作,但是没有重复的事件,这是我通常期望的(对于任何键)。当我释放on键时,我看到了“释放”操作,但当我按下(并按住它)时,没有生成新的“按”操作。

我尝试了key bindings API(如上面所示),但仍然没有成功(类似的结果)。

然后,我将AWTEventListener直接附加到事件队列,并监视所有的键击。

 类似资料:
  • 问题内容: 我有以下方法: 我想使其成为一种通用方法,这样我就不必为每个新的自定义类型编写新的代码。我可以这样做,这需要在调用update()之前实例化该对象: 出于好奇,我想知道是否有一种方法可以使用Java泛型来做到这一点: 有没有办法用Java做到这一点? 问题答案: 请注意,在这种情况下将可以修复。任一(其本身包括可从获得)或本身已得到通过。

  • 好的,我创建了一个名为game1的Game实例,但我如何在其他方法中使用game1的相同实例呢?这是我目前所拥有的 这是我的游戏类中的全部显示方法

  • 问题内容: 我想创建一个可以用插件扩展的Java程序。我该怎么做?我应该在哪里寻找? 我有一组插件必须实现的接口,它应该在一个jar中。程序应该在relative(相对于程序)文件夹中观察新的jar并以某种方式注册它们。 虽然我确实喜欢EclipseRCP,但我认为它对于我的简单需求来说太多了。 春天也是一样,但既然我无论如何都要看,我还是试试看吧。 不过,我还是希望能找到一种尽可能简单的方法来创

  • 问题内容: 开始听说“ POJO”(普通的旧Java对象)。我用谷歌搜索,但仍然不太了解这个概念。谁能给我关于POJO的清晰描述? 考虑带有变量“ id,名称,地址,薪水”的“人员”类-在这种情况下我将如何创建POJO?代码在POJO下方吗? 问题答案: POJO只是一个普通的,已删除限制的Java Bean。Java Bean必须满足以下要求: 默认的无参数构造函数 对于名为foo的可变属性,遵

  • 当使用谷歌服务库时,我在Android编程中看到了一种编码风格,在初始化类实例后使用dots调用方法。 例如,假设我有一个Person类: 现在,当我创建这个类的实例时,我希望能够执行以下操作: 然而,这给了我语法错误。我如何构建一个类来实现这一点?

  • 本文向大家介绍使用js如何创建一个private方法?相关面试题,主要包含被问及使用js如何创建一个private方法?时的应答技巧和注意事项,需要的朋友参考一下 可以利用闭包实现这一点: 另外一提,根据tc39的私有方法提案目前已进入Stage 3阶段,目测很快就会在个大浏览器和node等其他js环境实装,其语法如下: