按住键后如何摆脱延迟?

时间:2019-06-30 14:07:54

标签: java swing keylistener

我有一个移动两个正方形的程序。但是,每当我按住某个键时,正方形都会在网格上连续移动,这会有一段延迟。怎么样 我可以摆脱这种延迟吗?

我使用了for循环来遍历所有按下的键,以便一次按下多个键。

这是我的代码:

package com.Arman;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashSet;

public class Main {

    static int x1 = 0;
    static int y1 = 0;
    static Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    static int height = (int) dimension.getHeight();
    static int width = (int) dimension.getWidth();
    static int x2 = width - 100;
    static int y2 = height - 120;
    static myGraphicsPanel graphics = new myGraphicsPanel();

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JPanel left = new JPanel();
        JTextField text1 = new JTextField();
        text1.addKeyListener(new keyListener());
        left.add(text1);
        JTextField text2 = new JTextField();
        text2.addKeyListener(new keyListener());
        JPanel right = new JPanel();
        right.add(text2);
        frame.add(left);
        frame.add(right);
        frame.add(graphics);
        frame.setVisible(true);
        while (true) {
            frame.repaint();
        }
    }

    static class keyListener extends KeyAdapter {
        private HashSet<Integer> pressed = new HashSet<>();

        public void keyPressed(KeyEvent e) {
            pressed.add(e.getKeyCode());
            for (int f : pressed) {
                if (f == KeyEvent.VK_W) y1 = Math.max(y1 - 10, 0);
                if (f == KeyEvent.VK_A) x1 = Math.max(x1 - 10, 0);
                if (f == KeyEvent.VK_S) y1 = Math.min(y1 + 10, height - 120);
                if (f == KeyEvent.VK_D) x1 = Math.min(x1 + 10, width - 100);
                if (f == KeyEvent.VK_DOWN) y2 = Math.min(y2 + 10, height - 120);
                if (f == KeyEvent.VK_LEFT) x2 = Math.max(x2 - 10, 0);
                if (f == KeyEvent.VK_RIGHT) x2 = Math.min(x2 + 10, width - 100);
                if (f == KeyEvent.VK_UP) y2 = Math.max(y2 - 10, 0);
            }
        }

        public void keyReleased(KeyEvent e) {
            pressed.remove(e.getKeyCode());
        }

        public void keyTyped (KeyEvent e) {
            // not used
        }
    }

    static class myGraphicsPanel extends JPanel {
        public void paintComponent(Graphics g) {
            g.setColor(Color.BLUE);
            g.fillRect(x1, y1, 100, 100);
            g.setColor(Color.RED);
            g.fillRect(x2, y2, 100, 100);
        }
    }
}

0 个答案:

没有答案