有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA SWING使用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());
        }
    }

}

共 (1) 个答案

  1. # 1 楼答案

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

    相反,你应该:

    • 创建一个new Timer(100, ...),每10秒触发一次
    • 在实例字段中存储计时器开始时的开始时间(可能在按钮的ActionListener中这样做)
    • 在计时器的ActionListener中,获取当前毫秒数,并使用它检查经过的时间
    • 一整秒钟过后,通过((Timer) e.getSource()).stop();停止计时器
    • 不需要标志,因为您所需要做的就是检查计时器是否为null,以及它是否为.isRunning()。e、 然后动画正在进行

    无关建议:

    • 走出静态世界,进入实例世界。您正在使用Java编程,这是一种从一开始就使用OOPs的语言,您不想与OOPs范式抗争