【问题标题】:Java - KeyListener: Capture input within given timeframeJava - KeyListener:在给定的时间范围内捕获输入
【发布时间】:2015-10-23 01:37:15
【问题描述】:

我目前正在使用条形码阅读器进行项目。

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

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

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

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

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

我不知道条码有多长,有的短一些,有的长一些。

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

我将如何创建这样的方法?

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

【问题讨论】:

  • 那么,现在怎么办?你希望我们为你工作?你看 - 你的问题没有问题;只是暗示有人可能会向你扔所有代码。请更具体 - 从一些代码开始;并带着一个真正的问题回来..
  • 在检测到第一个字符时启动某种Timer(可能是Swing Timer),当计时器触发时,获取您捕获的所有字符并重置缓冲区。
  • @Jägermeister 当然不是。那只是我的一个想法。从逻辑上讲,我不知道如何开始,也不知道它是否有意义。
  • 也可以考虑SwingWorker
  • @MadProgrammer 谢谢,我会试试的

标签: java swing timer barcode keylistener


【解决方案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
    }
}

对于并发问题应该没问题,但要确保可以使用 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 2022-12-22
    • 2021-05-16
    • 2014-09-28
    • 1970-01-01
    • 2012-08-08
    相关资源
    最近更新 更多