[英]Java - KeyListener: Capture input within given timeframe
我目前正在使用条形码阅读器进行项目。
我有一个GUI和一个JTable
,上面已经应用了keyListener
。
基本上,我想扫描条形码并将数据库中的相应元素添加到JTable
。
当我扫描条形码(使用e.getKeyChar()
)时,它将在短时间内(毫秒)单独发送字符。
因此,我想将给定时间(比如说100毫秒)中的所有字符都存储在String中,以便将其分组为一个项目。
以后我可以用它在数据库中查找该项目。
我不知道条形码多长时间,其中一些短而又长。
我正在考虑使用System.currentTimeMillis()
并找出一个计时器,以便一旦有输入,计时器就会在100毫秒后启动和停止,然后将在该时间范围内键入的所有字符存储到数组或字符串中。
我将如何创建这种方法?
感谢您能提供的任何帮助。
对于关键的监听者,请尝试使用与此类似的内容
这主要是为了在第一次按下时使用计时器的逻辑
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之后检查线程,而是使用长计时器来检查每次按下/键入/释放键时的时间,并在添加到菜单之前调用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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.