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

问题描述 投票:0回答:1

我正在尝试设置一个程序,使用户在单击下一个和上一个按钮时可以显示过渡。当按下下一步时,摆动计时器应触发并开始动画。过渡时,应该有一个标志指出它处于过渡期间。 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());
        }
    }

}
java swing timer flags cardlayout
1个回答
1
投票

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

相反,您应该:

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