我为此感到挣扎。在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的新手,如果有人可以提供帮助,那就太好了

最佳答案

您可以利用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()

10-04 17:57