如何使用 Swing 制作方法,使用定时器休眠

How To Make a Method Using Swing, Sleep Using a Timer

我最近制作了一个小益智游戏,涉及点击特定区域。我还制作了一个解算器,它可以激活获胜所需的区域。我面临的问题是,每次它激活一个区域以创建一种 "solving animation" 时,我都想暂停。我的问题在这里

package experiment; 
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ExperimentHere extends JFrame implements ActionListener
{

private static final long serialVersionUID = 1L;
private JButton changeLabelButton;
private JPanel mainPanel;
private JLabel labelToChange;

public ExperimentHere() {
    changeLabelButton = new JButton("Set the label");
    changeLabelButton.addActionListener(this);

    mainPanel = new JPanel();

    labelToChange = new JLabel();
    labelToChange.setText("This needs to be changed");


    mainPanel.add(labelToChange);
    mainPanel.add(changeLabelButton);
    this.add(mainPanel);

    setTitle("Timer Program");
    setContentPane(mainPanel);

    setPreferredSize(new Dimension(1000, 1000));
    pack();

}

public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(changeLabelButton)){
        changeLabel();
    }
}

public void changeLabel(){
    for (int i = 0; i<5; i++){
        labelToChange.setText(""+i);
        // Pause for 200ms here

    }
}

public static void main(String[] args){
    ExperimentHere test = new ExperimentHere();
    test.setVisible(true);
   }
}

我试过使用定时器,但我不确定如何正确格式化它,以便它只在每次 changeLabel() 内的循环递增时暂停,因为 Timer() 中的第二个参数要求一个动作监听器。 我也试过使用 Thread.sleep() 但它只会冻结我的程序然后立即解决它。

理想情况下,changeLabel 方法会递增 1,将标签设置为新字符串,等待 200 毫秒,然后再次递增。

I have tried using Timers, but I'm not sure how to format it properly so that it only pauses each time the loop inside of changeLabel() is incremented

当您使用 Timer 时,您不使用循环。 Timer 的要点是您启动计时器并一直执行直到您停止 Timer

你也没有创建方法,你创建了一个 Action 来在 Timer 触发时调用。

因此您需要在 class 中有一个实例变量来跟踪计时器触发的次数(我们称它为 "timerCounter")。然后你需要创建一个 Action 来在每次触发 Timer 时调用。

所以你创建了几个实例变量:

int timerCounter = 0;
Action action;

然后在 class 的构造函数中创建一个类似于以下内容的 Action:

action = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        labelToChange.setText("" + timerCounter);
        timerCounter++;

        if (timerCounter > 5)
        {
            Timer timer = (Timer)e.getSource();
            timer.stop();
        }
    }
}

所以现在在 ActionListener 你的按钮中你可以做这样的事情:

timerCounter = 0;
Timer timer = new Timer(200, action);
timer.start();