有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing Java KeyListener:在给定的时间范围内捕获输入

我目前正在做一个使用条形码阅读器的项目

我有一个GUI和一个JTable,我在上面应用了一个keyListener

基本上,我想扫描一个条形码,并将数据库中相应的元素添加到JTable

当我扫描条形码(使用e.getKeyChar())时,它会在短时间(毫秒)内分别发送字符

因此,我想将给定时间(比如100毫秒)内的所有字符存储在一个字符串中,以便将其分组为一个项目

我可以稍后用它在数据库中查找该项目

我不知道条形码有多长,有些更短,有些更长

我在考虑使用System.currentTimeMillis()并计算出一个计时器,这样一旦有输入,计时器就会在100毫秒后启动和停止,然后将在该时间范围内键入的所有字符存储到一个数组或字符串中

我将如何创建这样一种方法

我很感激能得到的任何帮助


共 (1) 个答案

  1. # 1 楼答案

    对于密钥侦听器,请尝试使用类似的方法

    这主要是为了在第一次按下时使用计时器的逻辑

    new KeyListener()
    {
        LinkedList<KeyEvent> list = new LinkedList<KeyEvent>(e);
    
        public void keyPressed(KeyEvent e)
        {
            if(list.peek() == null)
                startTimer();
            list.push(e);
        }
    
        public void keyReleased(KeyEvent e)
        {
            if(list.peek() == null)
                startTimer();
            list.push(e);
        }
    
        public void keyTyped(KeyEvent e)
        {
            if(list.peek() == null)
                startTimer();
            list.push(e);
        }
    
        private void startTimer()
        {
            new Thread()
            {
                public void run()
                {
                    sleep(100);
                    doStuff();
                }
            }.start();
        }
    
        private void doStuff()
        {
            //do stuff with the list using list.pop() - export to string and what not and end up with an empty list
        }
    }
    

    对于并发性问题,它基本上是可以接受的,但为了确保可以使用列表作为同步锁

    如果你使用类似的东西,你也可以使用一个线程,但是不要用一个线程在100毫秒后检查,而是用一个长计时器来检查每次按键/键入/释放的时间,并在添加到堆栈之前调用doStuff

    new KeyListener()
    {
        LinkedList<KeyEvent> list = new LinkedList<KeyEvent>(e);
        long startTime;
    
        public void keyPressed(KeyEvent e)
        {
            if(System.currentTimeMillis() - startTime > 100)
                doStuff();
            list.push(e);
        }
    
        public void keyReleased(KeyEvent e)
        {
            if(System.currentTimeMillis() - startTime > 100)
                doStuff();
            list.push(e);
        }
    
        public void keyTyped(KeyEvent e)
        {
            if(System.currentTimeMillis() - startTime > 100)
                doStuff();
            list.push(e);
        }
    
        private void doStuff()
        {
            //do stuff with the list using list.pop() - export to string and what not and end up with an empty list
            startTime = System.currentTimeMillis();
        }
    }
    

    请注意,此设置不会自动处理最后扫描的条形码

    条形码将在下一个条形码开始时处理,这意味着您需要在程序结束时输入一些虚拟数据以获得最后一个条形码,或者以某种方式在侦听器上手动调用doStuff()