JAVA SWING - 使用 Swing 定时器创建动画

JAVA SWING - Creating Animation using Swing Timer

我正在尝试设置一个程序,使用户能够在单击下一个和上一个按钮时显示过渡。当按下下一步时,摆动计时器应该触发并开始动画。过渡时,应该有一个标志,表明它处于过渡期。 Swing 定时器应该每十分之一秒触发一次,基本上持续 1 秒。

public class guiCreation {
static Timer timer;
static boolean flag = false; 
private static void guiInterface() {
next.addActionListener(new ActionListener(){
            timer = new Timer(1000, this);
            public void actionPerformed(ActionEvent e){
                nextGest();
            }
        });
        //should go to the next tab
        previous.addActionListener(new ActionListener(){
            //if the list gets to the beginning, disable button
            public void actionPerformed(ActionEvent e){
                prevGest();
            }
        });
}
public static void nextGest() {
        timer.start();
        previous.setEnabled(true);
        next.setEnabled(true);
        //if the list gets to the end, disable button
        if (cardLayout.isNextCardAvailable()) {
            status.setText(" Next button has been clicked");
            //System.out.println("This is the" + size);
            cardLayout.next(cardPanel);
            next.setEnabled(cardLayout.isNextCardAvailable());
        }
    }
    public static void prevGest() {
        if (cardLayout.isPreviousCardAvailable()) {
            timer.start();
            next.setEnabled(true);
            previous.setEnabled(true);
            status.setText(" Previous button has been clicked");
            cardLayout.previous(cardPanel);
            previous.setEnabled(cardLayout.isPreviousCardAvailable());
        }
    }

}

这个:"The Swing timer should fire once every tenth of a second ..." -- 不同意这个:timer = new Timer(1000, this);你的计时器每秒触发一次,而不是每十分之一秒。

相反,您应该:

  • 创建一个 new Timer(100, ...),每十分之一秒触发一次
  • 在计时器开始时以毫秒为单位在实例字段中存储开始时间(可能在按钮的 ActionListener 中执行此操作)
  • 在计时器的 ActionListener 中获取当前的毫秒数并使用它来检查经过的时间
  • 经过 1 秒后,通过 ((Timer) e.getSource()).stop(); 停止计时器
  • 不需要标志,因为您需要做的就是检查 Timer 是否不为 null 以及它是否 .isRunning()。例如,if (timer != null && timer.isRunning()) {——然后动画继续。

不相关的建议:

  • 跳出静态世界,进入实例世界。您正在使用 Java 进行编程,这是一种为从头开始使用 OOP 而构建的语言,并且您不想与 OOP 范式作斗争。