javaactionlisteneractionevent

Choosing between multiple action events


So let´s just say I have 3 different ActionEvents and the class ExecuteAction should execute one of these event with the given integer action. Int action could be randomly generated or be given through a text field and all actionEvents should share the same Timer actionTimer.

Here´s a little concept of how I think it could work (It´s not a proper code, it´s just an idea).

public class ExecuteAction implements ActionListener{

private int action;
private Timer actionTimer = new Timer (delay, this);

   public ExecuteAction(){
       actionTimer.start();
       actionChooser(action);
      }

    private void actionChooser(int action){
         switch(action){
                case 1: //perform ActionEvent1 
                       break;
                case 2: //perform ActionEvent2
                       break;
                case 3: //perform ActionEvent3
                        break;
                   }
                }
}

Unfortunatly I don´t know how to handle it with the ActionListener and that´s where basically my ideas for this concept end. I would appriciate you helping me out finishing this concept.

Note: I don´t want to use any buttons, just the number should decide what actionEvent will be executed.


Solution

  • Just use the core Java pseudorandom number generator, java.util.Random, within your code, and random actions can be performed. If you place it within a standard ActionListener, then this can be called from within your Swing Timer. For example:

    // imports
    
    public class TimerFoo {
        private static final int TIMER_DELAY = 20; // or whatever delay desired
        private static final int MAX_CHOICE = 3;
        private ActionListener timerListener = new TimerListener();
        private Timer actionTimer;
        private Random random = new Random(); // import java.util.Random to use
    
        public ExecuteAction() {
            actionTimer = new Timer(TIMER_DELAY, () -> {
                int randomChoice = random.nextInt(MAX_CHOICE);
                switch (randomChoice) {
                    case 0:
                        // do code for 0;
                        return;
                    case 1:
                        // do code for 1;
                        return;
                    case 2:
                        // do code for 2;
                        return;
                    // don't need a default                 
                }
            });
        }
    
        public void start() {
            actionTimer.start();
        }
    }