Search code examples
javalibgdxswitch-statementbreak

Java: How can I "break" a switch-case after a specific time?


I have a method that renders items.

The problem I'm having is that I want the switch-case to break after 4.1 seconds. I don't want to use Thread.sleep, because it would freeze the entire screen on runtime.

This is what I tried, but it doesn't work:

private void drawItems(){
       itemSelected = randomInt.getValue3();
       switch (itemSelected){
           case 0: if (!Obstacle.case0) {
               doSomething();
           }
               new java.util.Timer().schedule(
                       new java.util.TimerTask() {
                           public void run() {
                                break;
                           }
                       },
                       4100
               );
// other cases

I want to break it because otherwise more than 1 item is being rendered on the screen, but the problem is that "break" needs to be outside switch or loop.


Solution

  • In the simplest form, something like:

    public class DrawingThread extends Thread {
        private boolean goon = true;
    
        public void run() { 
            //Drawing routine.. stop if goon is no longer true
        }
    
        public void requestStop() {
            goon = false;
        }
     }
    

    Then in your main method/driver class etc:

     DrawingThread dThread = new DrawingThread();
     dThread.start();
     //Other things, for instance try { Thread.sleep(4100) } catch (InterruptedException ie) {}
     dThread.requestStop();
    

    Some pointers at Jenkov.com, also in Oracle's java documentation. If that works well for you, look into reusing Thread objects, perhaps something under point 26 in the sidebar on that page would be useful.