문제

I am struggling a bit with this. After researching on Google I have created the following timer routine which works well when called

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

However, the problem is that I can't figure how to integrate this code into a JToggleButton which is the correct place for it so that when I click play it plays a move and when I click stop is stops (or pauses) the routine. Here is my JToggleButton code:

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

I am fairly new to Java and it would be great if someone could help

도움이 되었습니까?

해결책

You could take advantage of the 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);

Then in you button code you would simply call timer.start() or timer.stop()

다른 팁

I would suggest you make the playMovie method non-static & declare History as a global variable & include in your swing class:

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

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

Also, you will need to programmatically stop playMove() if its TimerTask thread is still running.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top