如何在 Java 中使用 keyTyped?

How do I use keyTyped in Java?

我曾经使用下面的扫描器 class 通过 cmd 提示符来侦听用户的输入,但我正在尝试让 Java 应用程序来侦听文本,而不是使用keyTyped 方法。

public static void main(String[] args) throws IOException {
    new AsteroidsGame();
    InputStream inputstream = new InputStream() {

        @Override
        public int read() throws IOException {
            return 0;
        }
    };
    try {
        FileOutputStream output = new FileOutputStream("HighScore.txt",true);
        Scanner input = new Scanner(System.in);
        PrintStream printStream = new PrintStream(output);
        printStream.println(input.next() + " " + points);
        printStream.close();
        System.out.println("Success!");
    }
    catch(IOException e){
        System.out.println(e);
    }
 }

我不知道如何处理让它监听击键并将字母组合成一个词的方法。 (这是获取游戏人物名字的一种方式)

@Override

public void keyTyped(KeyEvent e) {      
if(lives == 0)
    {
        e.getKeyCode() = KeyEvent.???
    }
}

如有任何建议,我们将不胜感激,因为 Java 图书馆和 Internet 的其他部分几乎无法提供示例或帮助。

如果你需要一个普通的listiners,那么你可以在任何java教程中找到它

如果你需要一个自定义监听器,你可以在这里看到: Create a custom event in Java

它有一个关于自定义 listuners 的好例子

您需要一个扩展 KeyAdapter class 的子class,这使您可以访问 KeyAdapter class 中的 keyPressed 方法,然后您可以重写该方法在你的程序中做你需要的。 KeyEvent e 是具有 getter getKeyCode 的 keyPressed 方法的参数,returns 一个特定的 int 取决于按下的键 See simple tutorial here。所以你的代码就像这样:

public class KL extends KeyAdapter {
    int k = 0;
    @Override
    public void keyPressed(KeyEvent e) {
        if (lives == 0) {
            k = e.getKeyCode();
        }
    }
}

Java 具有内置的 keyCodes 常量,因此您可以根据需要轻松使用它们,例如左键的 int 是 KeyEvent.VK_LEFT.

chapter 6 of Eck's excellent free text

中查看对此的更详细解释和 KeyEvent 听众的解释

当按下可以转换为有效 Unicode 字符的文本键时,它会生成 keyTyped 事件。我们可以抓住它。向上、向下等键可以由 e.getKeyCode() 事件类型处理。

public class SimpleKeyListener implements KeyListener {

    StringBuilder sb = new StringBuilder();

    @Override
    public void keyTyped(KeyEvent e) {
        sb.append(e.getKeyChar());
        System.out.println(sb.toString());
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_UP) {
            System.out.println("UP");
        } else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
            System.out.println("DOWN");
        }
    }
}

这里有一个 hello world 来测试它:

public class HelloWorldSwing {
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.addKeyListener(new SimpleKeyListener());

        JLabel label = new JLabel("Hello Swing");
        frame.getContentPane().add(label);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}