Keyboard events [JS + JAVA]

Js keyboard event 

In JavaScript, there are three keyboard events that can be used to handle keyboard input:

  1. keydown : Fires when the user presses any key on the keyboard. If the user holds down a key, this event will fire repeatedly until the key is released.

  2. keyup : Fires when the user releases any key on the keyboard.

  3. keypress : Triggered when the user presses a character key on the keyboard (including letters, numbers, symbols, etc.). In this case, the keydown and keyup events will not be fired.

example code

// addEventListener()函数添加事件监听器,以监听keydown、keyup和keypress事件
document.addEventListener("keydown", function(event) {
  console.log("Key down: " + event.key);
});

document.addEventListener("keyup", function(event) {
  console.log("Key up: " + event.key);
});

// keydown和keyup事件的key属性会获取到键的名称,而keypress事件的key属性会获取到键的字符。
document.addEventListener("keypress", function(event) {
  console.log("Key pressed: " + event.key);
});

JS function to handle keyboard events

  1. addEventListener(event, function, useCapture): Add an event listener to listen for keyboard events.

  2. removeEventListener(event, function, useCapture): Remove the event listener .

  3. event.keyCode: Get the keycode of the pressed key .

  4. event.key: Get the name of the pressed key .

  5. event.altKey: Indicates whether the Alt key was pressed .

  6. event.ctrlKey: Indicates whether the Ctrl key was pressed .

  7. event.shiftKey: Indicates whether the Shift key was pressed .

  8. event.metaKey: Indicates whether a special key (such as the ⌘ key or Windows key) was pressed .

  9. event.preventDefault(): Prevent browser default behavior.

  10. event.stopPropagation(): Stop event bubbling.

  11. setTimeout(function, delay) is used to execute the specified function once after the specified number of milliseconds

  12. clearTimeout(timeoutID): Cancel the timeout created by setTimeout().

  13. setInterval(function, delay): used to repeatedly execute the specified function at a specified time interval.

  14. clearInterval(intervalID): Cancel the interval created by setInterval().

 

JS handles continuous key events 

var intervalId = null;

document.addEventListener("keydown", function(event) {
  // 当用户按下ArrowRight键时,检查intervalId是否为null来确定setInterval()函数是否已经被启动
  if (event.key === "ArrowRight") {
    if (intervalId === null) {
      intervalId = setInterval(function() {
        console.log("ArrowRight key is pressed");
      }, 100);
    }
  }
});

document.addEventListener("keyup", function(event) {
  // 当用户释放ArrowRight键时,我们通过调用clearInterval()函数来停止setInterval()函数
  if (event.key === "ArrowRight") {
    clearInterval(intervalId);
    intervalId = null;
  }
});

Java keyboard events

Keyboard events in Java refer to pressing or releasing the keyboard in a window or component. In Java, you can use AWT or classes provided by Swing to handle keyboard events.

Handling keyboard events--steps 

  1. Implement a keyboard event listener : Listen to keyboard events (such as KeyListener or KeyAdapter) by implementing the KeyEvent listener interface provided by AWT or Swing in a class.

  2. Register listener : Register the keyboard event listener to the component to listen for keyboard events (such as JFrame, JPanel, etc.).

  3. Implement the keyPressed, keyTyped, and keyReleased methods : For events that occur when keys are pressed, released, and typed, Java provides three different methods to handle keyboard events.

Handle common keyboard events 

  1. Understand the value of keyCode : keyCode represents the numeric code of the key. The keyboard event class KeyEvent in Java contains a large number of constants to represent the keyCode values ​​of different keys, which can be accessed through KeyEvent.VK_*.

  2. Get the keyCode value : When processing keyboard events, you can get the keyCode value of the key through the getExtendedKeyCode() method of the KeyEvent object.

  3. Handling special keys : There are some special keys, such as Shift, Ctrl, Alt, etc. When processing these keys, you can look at the value returned by the getModifiers() method of the KeyEvent object to determine which special key was pressed.

  4. Handling key combination events : Sometimes, the user may press multiple keys to trigger an event, such as Ctrl + A to select all text. When handling combined key events, you must check whether all keys are pressed, and you must handle the keyCode values ​​of multiple keys.

  5. Handling continuous keypress events : In some cases, the user may need to press and hold a key to trigger an event continuously (for example, holding down an arrow key to control cursor movement). When processing a continuous key event, use the getID() method of the KeyEvent object to check the key type to determine whether the event is a press event or a release event. If it is a press event, you can use a timer to trigger the event repeatedly.

KeyCode comparison table

 

Handle continuous key events 

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.Timer;

public class ContinuousKeyExample implements ActionListener {
    private JFrame frame; // 声明一个JFrame对象
    private JTextField textField; // 声明一个JTextField对象
    private Timer timer; // 声明一个Timer对象
    private boolean isKeyPressed = false; // 声明一个布尔类型变量

    public static void main(String[] args) {
        JFrame frame = new JFrame(); // 创建一个新的JFrame对象
        frame.setSize(200, 200); // 设置JFrame的大小

        JTextField textField = new JTextField(); // 创建一个新的JTextField对象
        frame.add(textField); // 将JTextField添加到JFrame中

        ContinuousKeyExample listener = new ContinuousKeyExample(frame, textField); // 创建一个新的ContinuousKeyExample对象
        frame.addKeyListener(listener); // 向JFrame添加KeyListener

        frame.setVisible(true); // 显示JFrame
    }

    // 构造函数
    public ContinuousKeyExample(JFrame frame, JTextField textField) { 
        this.frame = frame; // 初始化成员变量
        this.textField = textField;
        this.timer = new Timer(100, this); // 创建一个新的Timer,以100ms间隔触发一次该对象的actionPerformed()方法
    }

    // 处理定时器事件
    @Override
    public void actionPerformed(ActionEvent e) {
        // 持续按键事件处理逻辑
        if (isKeyPressed) {
            textField.setText(textField.getText() + "x"); // 在JTextField上添加字符“x”
        }
    }

    // 启动定时器
    public void startTimer() {
        timer.start();
    }

    // 停止定时器
    public void stopTimer() {
        timer.stop();
    }

    // 判断定时器是否在运行
    public boolean isTimerRunning() {
        return timer.isRunning();
    }

    // 处理按键按下事件
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_X) { // 检查按下的键是否为x
            if (!isKeyPressed) { // 检查isKeyPressed标志是否已被设置为true
                isKeyPressed = true; // 将isKeyPressed标志设置为true
                startTimer(); // 启动定时器
            }
        }
    }

    // 处理按键释放事件
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_X) { // 检查释放的键是否为x
            isKeyPressed = false; // 将isKeyPressed标志设置为false
            stopTimer(); // 停止定时器
        }
    }

    public void keyTyped(KeyEvent e) {
        // 处理键入按键事件
    }
}

 

example code

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;

public class KeyEventExample implements KeyListener {
    public static void main(String[] args) {

        /*
         * JFrame是Java中表示窗口的一个类。
         * 它是Java Swing系列中的一部分,可用于创建GUI应用程序中的顶级窗口。 
         * JFrame类提供了许多方法,使我们可定制窗口的外观和行为,如设置窗口的大小,位置,标题等。
         */
        JFrame frame = new JFrame();
        frame.setSize(200, 200); // 设置窗口的大小为200x200像素(宽,高)
        frame.setVisible(true);  // 将窗口设置为可见,窗口将会显示在屏幕上
        frame.addKeyListener(new KeyEventExample()); // 在窗口中监听键盘事件
    
        // 添加菜单栏
        JMenuBar menubar = new JMenuBar();
        frame.setJMenuBar(menubar);
        // 添加菜单项
        JMenu menu = new JMenu("Menu");
        menubar.add(menu);
        // 设置加速键
        JMenuItem item = new JMenuItem("Item");
        item.addActionListener(new ComboKeyExample());
        item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_MASK));
        menu.add(item);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // 处理按下按键事件
        System.out.println("Key pressed: " + e.getKeyCode());
        // 检查Shift键是否同时按下
        if (e.isShiftDown()) {
            System.out.println("Shift key is down");
        }
        // 检查Ctrl键是否同时按下
        if (e.isControlDown()) {
            System.out.println("Ctrl key is down");
        }
        // 检查Alt键是否同时按下
        if (e.isAltDown()) {
            System.out.println("Alt key is down");
        }
        // 检查Ctrl+C键是否同时按下
        System.out.println("Ctrl+C pressed");
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // 处理键入按键事件
        System.out.println("Key typed: " + e.getKeyChar());
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // 处理释放按键事件
        System.out.println("Key released: " + e.getKeyCode());
        // 输出按键的名称
        int keyCode = e.getKeyCode();
        String keyText = KeyEvent.getKeyText(keyCode);
        System.out.println("Key released: " + keyText);
    }
}

 

Guess you like

Origin blog.csdn.net/Zhousan0125/article/details/131044680