我需要讓我的程序從鍵盤輸入數字,但需要輸入多個數字的數字。兩個或多個數字輸入的擊鍵之間的延遲
我的聽衆是這樣的:
class.getRootPane().getInputMap(JRootPane.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(49,0, false), "one");
class.getRootPane().getActionMap().put("one", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("1 pressed");
}
});
//2
class.getRootPane().getInputMap(JRootPane.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(50,0, false), "two");
class.getRootPane().getActionMap().put("two", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("2 pressed");
}
});
我建議有一個全球性的整數存儲,其中,如果明確會導致類似的動作:
if (numberfield.isEmpty()){
number = 1;
wait for half a second
if wait is over commit number to function and clear numberfield
}//resulting in "1"
else if (numberfield.isnotEmpty()){
"you must have caught it in time"
numberfield = "numberfield"+"1";
wait for half a second
if wait is over commit number to function and clear numberfield
}//resulting in "11" if 1 was pressed twice
我的問題是:什麼是實現這種「延遲」的最好方法。恐怕Thread.sleep(500);或類似的東西會導致我的聽衆停止工作。有沒有更容易的方法來做到這一點比設置一個計時器和檢查每半秒?
不理解你爲什麼需要延遲,你想達到什麼目的? – kleopatra
請注意'class'是一個保留[關鍵字](http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.9)。 – trashgod