Java JButton中的多个操作

Java JButton中的多个操作,java,user-interface,graphics,timer,jbutton,Java,User Interface,Graphics,Timer,Jbutton,在这个程序中,我们应该单击一个显示“开始”的按钮,然后动画将开始在屏幕上运行。单击“开始”后,该按钮将变为“暂停”按钮,如果单击该按钮,它将停止动画并显示“恢复”按钮。我不知道如何将这三个动作集中到一个按钮中。以下是我目前掌握的代码: JButton button = new JButton("Start"); button.addActionListener(new ActionListener() { public vo

在这个程序中,我们应该单击一个显示“开始”的按钮,然后动画将开始在屏幕上运行。单击“开始”后,该按钮将变为“暂停”按钮,如果单击该按钮,它将停止动画并显示“恢复”按钮。我不知道如何将这三个动作集中到一个按钮中。以下是我目前掌握的代码:

JButton button = new JButton("Start");
      button.addActionListener(new
         ActionListener()
         {
            public void actionPerformed(ActionEvent e)
            {
               Timer t = new Timer(100, new
                     ActionListener()
                     {
                        public void actionPerformed(ActionEvent event)
                        {
                           shape.translate(x, y);
                           label.repaint();
                        }
                     });
               t.start();
            }
         });
我知道这不对。当我运行程序时,动画处于空闲状态,直到我点击“开始”,这是正确的,但是每次我再次点击按钮,动画都会加速,这是不正确的。如何向按钮添加不同的操作

例如,在动画运行后,我希望“暂停”按钮在单击计时器时停止计时器,然后在单击“恢复”时恢复计时器。我现在的代码每次单击它时都会创建一个新的计时器对象,但这似乎是使其工作的唯一方法。如果我将任何内容放在ActionListener之外,就会得到一个范围错误。有什么建议吗

但每当我再次按下按钮,动画就会加速,这是不正确的

不要在
ActionListener
中不断创建
计时器。每次单击该按钮,都会启动一个新计时器

而是在类的构造函数中创建
计时器。然后在
ActionListener
中,您只需
start()
现有的
计时器

然后,
Pause
和“Resume
按钮也将调用现有计时器上的
stop()
restart()`方法

我知道这不对。当我运行程序时,动画处于空闲状态,直到我点击“开始”,这是正确的,但是每次我再次点击按钮,动画都会加速,这是不正确的

这是因为每次按下按钮时都会创建多个新的
计时器。您应该有一个对
计时器的引用,并根据计时器的当前状态决定要做什么

//...
private Timer timer;
//...

JButton button = new JButton("Start");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (timer == null) {
            timer = new Timer(100, new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    shape.translate(x, y);
                    label.repaint();
                }
            });
            timer.start();
            button.setText("Pause");
        } else if (timer.isRunning()) {
            timer.stop();
            button.setText("Resume");
        } else {
            timer.start();
            button.setText("Pause");
        }
    }
});

这是一个问题。我尝试过这样做,但是我得到了一个“不能引用在封闭范围内定义的非局部变量t”的问题。我唯一能做到这一点的方法是将计时器的构造函数放在“ActionListener”中。@GenericUser01您的示例代码没有足够的上下文来提供该问题的完整解决方案,除了:,尝试将
Timer
设置为类的实例字段。方法是重新构造代码,以便将计时器定义为类中的实例变量。非常感谢!这把它修好了。我知道我的方法是每次都创建一个新的计时器,这不是我想要的。我从未想过将计时器放在我的私有实例变量中。