开发者

Stopping a Swing timer until the user clicks

开发者 https://www.devze.com 2023-02-04 04:03 出处:网络
I\'m writing a card game. Right now I\'m having problems with mouse handling. Below is the timer that handles the game flow of drawing and discarding cards.

I'm writing a card game. Right now I'm having problems with mouse handling. Below is the timer that handles the game flow of drawing and discarding cards.

    final Timer timer = new Timer(1000, null);

    timer.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            b.players[p].drawCard();
            if(p==0) // player zero is the human player
            {
                timer.stop();
                // ...
                b.players[p].discardCard(i);
                timer.start();
            }
            else
                b.players[p].discardCard(0);
            p=(p+1)%4;
            b.repaint();
        }
    });

The thing is that I want to stop the timer, wait until the user clicks the card he wants to discard, then start the timer again. b implements MouseListener in a basic way:

public void mouseClicked(MouseEvent arg0) 
{
    clickX = arg0.getX();
    clickY = arg0.getY();
}

There's als开发者_开发技巧o the xYtoCardIndex() method somewhere out there.

What do I do here? I assume I have to do nothing in a nonblocking way, right?


In pseudo-code, in your MouseEventListener :

public void mouseClicked(MouseEvent arg0) 
{
    clickX = arg0.getX();
    clickY = arg0.getY();

    Card discarded = getCard(clickX,clickY);
    b.players[p].discardCard(discarded);

    // The card has been discarded, I can start my timer again.
    timer.start();
}

In your drawCard function :

    public void drawCard() {
        // Stop the timer
        timer.stop();

        // Do the drawing.
    }

This way, when the player draws a card, the timer stops until a card is discarded.


First, your code is not compiled:

b.players[p].discardCard(int i); contains a syntax error int i.

Second, I do not really understand the problem. Stop the timer when you want, implement your listener (i.e. mouse listener) that starts the timer.

Or probably I did not understand your question?

BTW I have just checked Timer API. It does not have neither start nor stop methods. You have to deal with specific tasks to control execution.

0

精彩评论

暂无评论...
验证码 换一张
取 消