需要帮助在JToggleButton后面放置一个计时器方法

时间:2012-07-17 21:34:48

标签: java swing timer jtogglebutton

我正在努力解决这个问题。在研究Google之后,我创建了以下计时器例程,该例程在调用

时效果很好
// play move method
public static void playMove() {
    int delay = 1200; // delay for 1 sec.
    int period = 1200; // repeat every sec.

    final Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        private int count = history.getGameIndex();

        public void run() {
            count++;
            if (count >= history.getTotalMoves() + 1) {
                timer.cancel();
                timer.purge();
                return;
            }
            history.next();
        }
    }, delay, period);
}

然而,问题是我无法想象如何将此代码集成到JToggleButton中,这是正确的位置,这样当我点击播放时它会播放,当我点击停止时停止(或暂停)例程。这是我的JToggleButton代码:

ImageIcon playIcon = new ImageIcon(
        JBoard.class.getResource("/images/menu/play.png"));

btnPlayMove = new JToggleButton(playIcon);
btnPlayMove.setToolTipText("Play");
btnPlayMove.setContentAreaFilled(true);
btnPlayMove.setMargin(new Insets(2, 2, 2, 2));

btnPlayMove.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent ie) {
        if (isConnected()) {
            showMessage("Engine disabled during network play...");
            return;
        } else if (btnPlayMove.isSelected()) {
            // play
            playMove();
            ImageIcon playIcon = new ImageIcon(JBoard.class
                    .getResource("/images/menu/play.png"));
            btnPlayMove.setIcon(playIcon);
        } else {
            // stop
            ImageIcon stop = new ImageIcon(JBoard.class
                    .getResource("/images/menu/stop.png"));
            btnPlayMove.setIcon(stop);

        }
    }
});
buttonPanel.add(btnPlayMove);

我对Java很新,如果有人可以提供帮助,那就太棒了

2 个答案:

答案 0 :(得分:1)

您可以利用javax.swing.Timer

Timer timer = new Timer(1200, new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        count++;
        if (count >= history.getTotalMoves() + 1) {
            timer.cancel();
            timer.purge();
            return;
        }
        history.next();
    }
});

timer.setRepeats(true);
timer.setCoalesce(true);
timer.setInitialDelay(1200);

然后在按钮代码中,您只需拨打timer.start()timer.stop()

即可

答案 1 :(得分:0)

我建议你让playMovie方法非静态&将历史声明为全局变量&包括在你的挥杆课程中:

History history = new History(); // assuming this with no-args

public void playMove() {
         int delay = 1200; // delay for 1 sec.
         // etc.
         // etc.
}

此外,如果TimerTask线程仍在运行,则需要以编程方式停止playMove()。