在多个动作事件之间进行选择

Choosing between multiple action events

所以假设我有 3 个不同的 ActionEvents,class ExecuteAction 应该使用给定的整数 action 执行其中一个事件。 Int action 可以随机生成或通过文本字段给出,所有 actionEvent 应共享相同的计时器 actionTimer

这是我认为它如何工作的一个小概念(这不是一个正确的代码,它只是一个想法)。

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

不幸的是,我不知道如何使用 ActionListener 来处理它,这基本上是我对这个概念的想法结束的地方。我会感谢你帮助我完成这个概念。

注意:我不想使用任何按钮,数字应该决定将执行什么 actionEvent。

只需在您的代码中使用核心 Java 伪随机数生成器 java.util.Random,即可执行随机操作。如果将它放在标准的 ActionListener 中,则可以从 Swing Timer 中调用它。例如:

// 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();
    }
}