You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Key Event Listener中按键按住的重复触发延迟?

Controlling Key Hold Repeat Delay in Swing

Great question! The default delay between the first key press and the start of repeated key triggers is controlled by your operating system's keyboard settings—so the standard KeyListener doesn't let you tweak this directly for your Swing app. But we can build our own custom key hold logic using a Swing Timer to get full control over the timing.

Here's how to modify your code to achieve this:

First, we'll add a few variables to track the key state and handle the repeated actions:

  • A Timer to schedule repeated movement when the key is held
  • A boolean flag to track if the left arrow key is currently pressed

Here's the full modified code with explanations:

import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;

public class CustomKeyRepeatExample {
    private static int x = 200; // Initial X position
    private static int y = 200; // Initial Y position
    private static Timer keyRepeatTimer;
    private static boolean isLeftKeyPressed = false;

    public static void main(String[] args) {
        JFrame thing = new JFrame();
        thing.setTitle("thing");
        thing.setResizable(false);
        thing.setSize(500, 500);
        JPanel panel = (JPanel) thing.getContentPane();
        panel.setLayout(null);
        JLabel thing2 = new JLabel("thing");
        panel.add(thing2);
        thing2.setBounds(x, y, 50, 50);
        thing2.setFocusable(true);
        thing2.requestFocusInWindow();

        // Initialize the repeat timer
        // The first argument is the repeat interval (ms between each repeated action)
        keyRepeatTimer = new Timer(50, (ActionEvent e) -> {
            if (isLeftKeyPressed) {
                thing2.setLocation(x - 10, y);
                thing2.repaint();
                x -= 10;
            }
        });
        // Set the initial delay: time (ms) between first press and start of repeats
        keyRepeatTimer.setInitialDelay(200);

        thing2.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int key = e.getKeyCode();
                if (key == KeyEvent.VK_LEFT && !isLeftKeyPressed) {
                    // Execute the action once immediately on first press
                    thing2.setLocation(x - 10, y);
                    thing2.repaint();
                    x -= 10;
                    // Mark the key as pressed
                    isLeftKeyPressed = true;
                    // Start the timer to repeat the action
                    keyRepeatTimer.start();
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                int key = e.getKeyCode();
                if (key == KeyEvent.VK_LEFT) {
                    // Mark the key as released
                    isLeftKeyPressed = false;
                    // Stop the repeat timer
                    keyRepeatTimer.stop();
                }
            }
        });

        thing.setVisible(true);
        thing.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Key Adjustments You Can Make:

  • Initial Delay: Change keyRepeatTimer.setInitialDelay(200) to adjust how long after the first press the repeated actions start (200ms = 0.2 seconds).
  • Repeat Interval: Change the first argument in new Timer(50, ...) to adjust how often the action repeats while the key is held (50ms = 0.05 seconds).

Why This Works Better Than Default KeyListener:

  • The default key repeat behavior is tied to system settings, which vary across operating systems and users. This approach lets you define consistent behavior for your app.
  • You have full control over both the initial pause and the repeat rate, so you can tune it to feel natural for your specific use case.

内容的提问来源于stack exchange,提问作者Bisous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:07:52