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

时间:2015-10-23 01:37:15

标签: java swing timer barcode keylistener

我目前正在使用条形码阅读器开展项目。

我有一个GUI和一个JTable,我已经应用了keyListener

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

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

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

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

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

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

我如何创建这样的方法?

我感谢我能得到的任何帮助。

1 个答案:

答案 0 :(得分:0)

对于您的密钥监听器,请尝试使用与此类似的东西

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

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
    }
}

对于并发问题应该是很好的,但要确保可以使用list作为同步锁

如果您使用类似的东西,也可以使用单个线程,但是在100ms后不使用Thread来检查,使用长计时器来检查每次按下/键入/释放键时的时间并在之前调用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()

相关问题