当前位置: 首页 > 图灵资讯 > 技术篇> KeyListener键盘监听器

KeyListener键盘监听器

来源:图灵教育
时间:2023-06-25 14:32:08

import javax.swing.*;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;//KeyListener:键盘监听publiccicctic class Keylistenertesttttest1 {    public static void main(String[] args) {        JFrame f=new JFrame();        f.setSize(500,500);        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);        f.addKeyListener(new KeyListener() {            @Override            public void keyTyped(KeyEvent e) {            }            @Override            public void keyPressed(KeyEvent e) {                int keyCode=e.getKeyCode();                if (keyCode==37){                    System.out.println(“左执行”);                }else if (keyCode==38){                    System.out.println(“向上执行”;                }else if (keyCode==39){                    System.out.println(“向右执行”;                }else if (keyCode==40){                    System.out.println(“向下执行”;                }            }            @Override            public void keyReleased(KeyEvent e) {            }        });        f.setVisible(true);    }}