键盘监听

键盘监听

以下代码对键盘输入做出反应:

package com.cxf.gui.Keyboard;


import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class TestForKeyboard {
    public static void main(String[] args) {
        new MyFrame();
    }
}

class MyFrame extends Frame{
    public MyFrame() {
        setVisible(true);
        setBounds(100, 100, 1000, 700);
        
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_UP){
                    System.out.println("key of up pressed");
                }
            }
        });

    }
}

输出结果:

key of up pressed
key of up pressed
key of up pressed

按下键盘↑键时,打印“key of up pressed”。

此处使用了keylistener,用以监听键盘。

posted on 2021-09-24 14:17  菜小疯  阅读(107)  评论(0编辑  收藏  举报