我目前正在编写汉诺塔游戏的代码。我想要一个自动版本,它使用我的算法并且每个步骤之间都有延迟。我已经尝试使用 Java 中的 Timer,但它仍然不起作用。
这是我的代码的计时器。
public void startDelay() {
ActionListener action = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
delayTimer.stop();
}
};
delayTimer = new Timer(delay, action);
delayTimer.setInitialDelay(500);
}
这是我想使用它的示例。
public void algorithm() {
while(tower3.count() != 3) {
move1();
move2();
move3();
}
}
public void move1() {
getHeadLength();
if (tower3.count() == 3) {
return;
}
if (headT1 > headT3 && headT3 != 0) {
getBlock(tower3);
startDelay();
setBlock(tower1);
startDelay();
commitChange();
startDelay();
return;
}
}
有人知道我如何实现它吗?
最佳答案
使用计时器
执行所需的操作(移动),如以下MRE所示.
以下演示中的操作只是在 JTextField
中写入文本:
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
public class SwingMain {
private int phase = 1;
private Timer moveTimer;
SwingMain() {
creategui();
}
void creategui(){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.add(new APanel());
f.pack();
f.setVisible(true);
}
class APanel extends JPanel{
private final JTextField tf;
private final JButton start;
APanel() {
start = new JButton("Start");
start.addActionListener(e-> startTimer());
add(start);
tf = new JTextField("Click Start",6);
add(tf);
}
void startTimer() {
start.setEnabled(false);
ActionListener action = e -> autoPlay();
moveTimer = new Timer(2000, action);
moveTimer.setInitialDelay(500);
moveTimer.start();
}
private void autoPlay() {
switch (phase){
case 1:
phase++;
move1();
break;
case 2:
phase++;
move2();
break;
case 3:
phase++;
move3();
break;
default:
phase = 1;
moveTimer.stop();
tf.setText("Click Start");
start.setEnabled(true);
break;
}
}
private void move1() {
tf.setText("Move 1");
}
private void move2() {
tf.setText("Move 2");
}
private void move3() {
tf.setText("Move 3");
}
}
public static void main(String[] args) {
new SwingMain();
}
}
关于java - 设置与 GUI (Java Swing) 自动交互之间的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58942023/