Search code examples
javaswinglistenerdelay

Delay between keystrokes for 2 or more digit number entry


I need to have my program take in numbers from the keyboard, but need to allow for numbers of multiple digits to be entered.

My listeners look like this:

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");
    }
});

I am proposing to have a global integer stored, which, if clear would cause an action like:

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

My question is this: what is the best way to implement this "delay" I am afraid Thread.sleep(500); or something of the like would cause my listeners to stop working. It there an easier way to do this than setting up a timer and checking every half a second?


Solution

  • I'm not sure what you are doing based on the posted code. You are attempting to use the root pane which would indicate you don't have any focusable components on your GUI.

    The easiest solution is to add DocumentListener to each text field. Whenever a DocumentEvent is generated you start/restart a Timer. If the Timer fires then you commit the number and clear the field.

    If you are doing this for all text fields on the GUI then it might be easier to check out Global Event Listeners. You should be able to use a KeyEventPostProcessor. Every time a KeyEvent is generated your restart your Timer. If the Timer fires then you commit the number and clear the field.