如何使用Timer在特定时间引发操作

时间:2016-05-09 23:42:44

标签: java timer

我正在编写一个使用倒数计时器的程序。当用户点击"新游戏"按钮,程序将选择1到1000之间的随机数,用户必须在30秒内猜出正确的价格。所以我有时间工作,但我不确定如何显示用户在30秒内猜测正确答案需要多长时间。 目前在我的代码中(这是在私有类Answerlistener下,我的代码的其余部分位于底部):

myTimer1.stop();
double timer = 30.0 - myTimer1.stop();
messageLabel.setText("Correct! It took you " + countTotal + " tries, in " + timer  + " seconds");
messageLabel.setBackground(Color.yellow);

但是,我一直收到双倍计时器的错误信息,所以我知道这是不对的,但我不知道如何解决它。此外,如果计时器在用户猜到正确答案之前达到0,我想要消息"你输了"要显示。目前在我的代码中(我在私有类Answerlistener下):

else if (sum > answer && myTimer1 == 0)
{
    messageLabel.setText("You Lose");
}
else if (sum < answer && myTimer1 == 0)
{
    messageLabel.setText("You Lose");
}

但是我再次收到myTmer1 == 0的错误消息,所以我知道这是不对的,但我不知道如何修复它。那么我怎么能打印我的程序&#34;你失去了#34;如果用户没有猜到正确的答案,并且计时器等于0。任何帮助将不胜感激。

以下是我的所有代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

public class ClockGame extends JFrame {

    //Declare fields for GUI components
    private JTextField guessField;
    private JButton newGameButton;
    private JLabel messageLabel;
    private JLabel guessLabel;
    private ImageIcon clockImage;
    private int countTotal;
    private Random rand;
    private JLabel title;
    private int number;
    private Timer myTimer1;
    public static final int ONE_SEC = 1000;   //time step in milliseconds
    public static final int TENTH_SEC = 100;
    private Font myClockFont;
    private JLabel timeLbl;
    private int clockTick;      //number of clock ticks; tick can be 1.0 s or 0.1 s
    private double clockTime;   //time in seconds
    private String clockTimeString;

    public ClockGame() {
        //Build GUI
        super ("Clock Game");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set layout
        this.setLayout(new BorderLayout());

        //Create the main panel
        JPanel mainPanel = new JPanel();

        //Create components and place them in the panel
        rand = new Random();

        guessLabel = new JLabel("Guess: ");
        guessField = new JTextField(20);
        messageLabel = new JLabel("                             Click New Game to Begin");
        clockImage = new ImageIcon("clock.jpg");
        newGameButton = new JButton("New Game");
        title = new JLabel("The Clock Game", clockImage, SwingConstants.CENTER);

        clockTick = 300;        //initial clock setting in clock ticks
        clockTime = ((double)clockTick)/10.0;

        clockTimeString = new Double(clockTime).toString();
        myClockFont = new Font("Serif", Font.PLAIN, 20);

        timeLbl = new JLabel();
        timeLbl.setFont(myClockFont);
        timeLbl.setText(clockTimeString);


        //Set font for clockGameLabel
        title.setFont(new Font("Calibri", Font.BOLD, 24));

        //Set messageLabel Color
        messageLabel.setOpaque(true);
        messageLabel.setBackground(Color.yellow);

        newGameButton.addActionListener(new ButtonListener());

        guessField.addActionListener(new AnswerListener());

        //Add components to the panel
        mainPanel.add(guessLabel);
        mainPanel.add(guessField);
        mainPanel.add(newGameButton);
        this.add(title, BorderLayout.NORTH);
        this.add(messageLabel, BorderLayout.SOUTH);

        mainPanel.add(timeLbl);


        //Add the panel to this JFrame
        this.add(mainPanel, BorderLayout.CENTER);

        //Sizes this JFrame so that it is just big enough to hold the components
        this.setSize(340,225);

        //Make the JFrame visible on the screen
        this.setVisible(true);
    }

    private class AnswerListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            //Code to check to see if answer is correct
            int sum = number;
            int answer = Integer.parseInt(guessField.getText());
            guessField.selectAll();
            Color purple = new Color(153, 153, 253);

            countTotal++;
            if (sum < answer)
            {
                messageLabel.setText("Too High");
                messageLabel.setBackground(Color.red);
            }
            else if (sum > answer)
            {
                messageLabel.setText("Too Low");
                messageLabel.setBackground(purple);
            }
            else if (sum > answer && myTimer1 == 0)
            {
                messageLabel.setText("You Lose");
            }
            else if (sum < answer && myTimer1 == 0)
            {
                messageLabel.setText("You Lose");
            }
            else
            {
                myTimer1.stop();
                double timer = 30.0 - myTimer1.stop();
                messageLabel.setText("Correct! It took you " + countTotal + " tries, in "
                 + timer  + " seconds");
                messageLabel.setBackground(Color.yellow);            
            }
        }
    }

    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            number = rand.nextInt(1001);
            messageLabel.setText("              The price is between $1 and $1000, begin.");
            messageLabel.setBackground(Color.green);
            countTotal = 0;
            clockTick = 300;
            clockTime = ((double)clockTick)/10.0;
            clockTimeString = new Double(clockTime).toString();
            timeLbl.setText(clockTimeString);
            myTimer1 = new Timer(TENTH_SEC, new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    clockTick--;
                    clockTime = ((double)clockTick)/10.0;
                    clockTimeString = new Double(clockTime).toString();
                    timeLbl.setText(clockTimeString);
                    //System.out.println(clockTime);
                }
            });
            myTimer1.start();
        }
    }

    public static void main(String[] args) {
        ClockGame frame = new ClockGame();
    }
}

1 个答案:

答案 0 :(得分:1)

我认为您需要在Timers动作侦听器的动作执行方法中检查计时器是否已达到0。如果定时器已达到0显示消息。