所以我们假设我有3个不同的ActionEvents,类ExecuteAction
应该用给定的整数action
执行其中一个事件。Int action
可以随机生成或通过文本字段给出,并且所有actionEvents都应该共享相同的TimeractionTimer
。
以下是我认为它如何工作的一个小概念(这不是一个合适的代码,只是一个想法(。
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();
}
}