【问题标题】:Multiple Actions in a JButtonJButton 中的多个操作
【发布时间】:2015-10-07 01:45:38
【问题描述】:

在这个程序中,我们应该单击一个“开始”按钮,然后动画将开始在屏幕上运行。在我们单击“开始”后,该按钮将变为“暂停”按钮,如果单击它,它将停止动画并出现“恢复”按钮。我不确定如何将所有这三个操作都集中到一个按钮中。这是我到目前为止的代码:

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();
            }
         });

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

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

【问题讨论】:

    标签: java user-interface graphics timer jbutton


    【解决方案1】:

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

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

    //...
    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");
            }
        }
    });
    

    【讨论】:

    • 非常感谢!这解决了它。我知道我拥有它的方式是每次都创建一个新的计时器,这不是我想要的。我从没想过将计时器放在我的私有实例变量中。
    【解决方案2】:

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

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

    而是在类的构造函数中创建Timer。然后在ActionListener 中你只需start() 现有的Timer

    然后是现有 Timer 上的 Pause 和 'Resumebuttons will also just invoke thestop()andrestart()` 方法。

    【讨论】:

    • 这是个问题。我试过这样做,但我得到一个“不能引用在封闭范围中定义的非局部变量 t”我可以让它工作的唯一方法是将 Timer 的构造函数放在“ActionListener”中。跨度>
    • @GenericUser01 您的示例代码没有足够的上下文来为该问题提供完整的解决方案,除了说,尝试将 Timer 设为类的实例字段
    • 这样做的方法是重构代码,以便将 Timer 定义为类中的实例变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2012-11-27
    相关资源
    最近更新 更多