[英]Repeated down arrow key pressed in Jtable
On JTable
, when down arrow key is pressed repeatedly, multiple KeyEvents are fired in quick succession. 在
JTable
,当反复按下向下箭头键时,会快速连续触发多个KeyEvent。 My requirement is that I need to act only on last KeyEvent
. 我的要求是我只需要在最后一个
KeyEvent
上行动。 I am trying to use TimerTask
in KeySelectionListener
, but it is giving inconclusive results. 我试图在
KeySelectionListener
使用TimerTask
,但它给出了不确定的结果。
Any idea what changes can be done in KeyListener
? 知道
KeyListener
可以做些什么改变吗?
Sample code - 示例代码 -
addKeyListener(new KeyListener() {
Timer t = new Timer();
TimerTask tt;
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
tt.cancel();
tt = null;
}
@Override
public void keyPressed(KeyEvent e) {
if (tt != null)
return;
tt = new TimerTask() {
@Override
public void run() {
System.out.println("Selected-- "+getModel().getValueAt(getSelectedRow(), 2));
}
};
// t.scheduleAtFixedRate(tt, 0, 500);
t.schedule(tt, 0, 200);
}
});
Thanks 谢谢
The idea with a Timer
(and I strongly suggest to use the javax.swing.Timer
class since you interact with Swing components) should work. 使用
Timer
的想法(我强烈建议您使用javax.swing.Timer
类,因为您与Swing组件交互)应该可以工作。
Just set the repeats to false
, start the timer when you receive a keystroke if the timer is not running, or restart the timer when the timer is already running. 只需将重复设置为
false
,如果计时器未运行,则在收到击键时启动计时器,或者在计时器运行时重新启动计时器。 This will cause a slight delay in the handling of the last key (delay = the delay you set on the timer), but avoid that you react on each key stroke 这将导致最后一个键处理的轻微延迟(延迟=您在计时器上设置的延迟),但避免您对每个键击的反应
I used Timer only. 我只用过Timer。 I maintained reference of KeyEvent in listener and if another KeyEvent is received in pre-defined delay (for testing kept it 1 sec), new event is referneced.
我在监听器中维护了KeyEvent的引用,如果在预定义的延迟中接收到另一个KeyEvent(为了测试保持1秒),则引用新事件。 Thus when there is no new keyEvent for 1 sec, last referred event is used for further processing.
因此,当1秒没有新的keyEvent时,最后引用的事件用于进一步处理。 its working for now.
它现在工作。 Feel free to suggest your opinions.
随意提出您的意见。
addKeyListener(new KeyListener() { addKeyListener(new KeyListener(){
KeyEvent eventToProcess;
Timer t = new Timer();
TimerTask tt;
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(tt != null){
tt.cancel();
tt = null;
}
}
@Override
public void keyReleased(KeyEvent e) {
eventToProcess = e;
tt = new TimerTask() {
@Override
public void run() {
System.out.println("Selected-- "+getModel().getValueAt(getSelectedRow(), 2)+" Key Event > "+eventToProcess.getKeyChar());
}
};
t.schedule(tt, 1000);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.