Question

i want to use keyPressed function in canvas class. but i do not want immediately call this function.
i try to use wait function but it cause an error ( i think it hasn't any use for this). what should i do?

Was it helpful?

Solution

keyPressed is called by the AMS (Application Management Software) when the user clicks a key. You cannot delay that. But you can of course call keyPressed yourself as you want. If you want to call keyPressed 10 seconds from now, you should create a Thread with a timer and a loop that asks if 10 seconds has gone by now. Something like this: (not tested)

class keyPressedAfterSeconds implemments Runnable {

  MyCanvasObject myCanvas = null;
  int seconds = 10; // Default
  long startTime;

  public keyPressedAfterSeconds(MyCanvasObject myCanvas, int seconds) {

    this.myCanvas = myCanvas;
    this.seconds = seconds;
    new Thread(this).start();

  }

  public run() {

    startTime = System.currentTimeMillis();
    while(System.currentTimeMillis()-startTime<seconds*1000) {
      try { // Wait 100 ms and ask again
        Thread.sleep(100);
      } catch (Exception e) {}
    }
    myCanvas.keyPressed(someKeycode);

  }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top