java - 倒数计时器帮助

标签 java timer applet countdown

我用java Applet制作了一个益智游戏,我需要添加一个运行5分钟的计时器,玩家必须在这段时间内解决谜题,如果没有,就会出现一个对话框要求重试,所以我需要计时器重新启动。

有人可以告诉我如何编码吗?

  public void init (){
 String MINUTES = getParameter("minutes");
 if (MINUTES != null) remaining = Integer.parseInt(MINUTES) * 600000;
 else remaining = 600000; // 10 minutes by default

 // Create a JLabel to display remaining time, and set some PROPERTIES.
 label = new JLabel();
// label.setHorizontalAlignment(SwingConstants.CENTER );
// label.setOpaque(false); // So label draws the background color




 // Now add the label to the applet. Like JFrame and JDialog, JApplet
 // has a content pane that you add children to
  count.add(label);
  Puzframe.add(count,BorderLayout.SOUTH);


 // Obtain a NumberFormat object to convert NUMBER of minutes and
 // seconds to strings. Set it up to produce a leading 0 if necessary
 format = NumberFormat.getNumberInstance();
 format.setMinimumIntegerDigits(2); // pad with 0 if necessary

 // Specify a MouseListener to handle mouse events in the applet.
 // Note that the applet implements this interface itself


 // Create a timer to call the actionPerformed() method immediately,
 // and then every 1000 milliseconds. Note we don't START the timer yet.
 timer = new Timer(1000, this);
 timer.setInitialDelay(0); //
 timer.start(); }



public void start() { resume(); }



  //The browser calls this to stop the applet. It may be restarted      later.
  //The pause() method is defined below

void resume() {
  // Restore the time we're counting down from and restart the timer.
 lastUpdate = System.currentTimeMillis();
 timer.start(); // Start the timer
}`

//Pause the countdown



void updateDisplay() {
 long now = System.currentTimeMillis(); // current time in ms
 long elapsed = now - lastUpdate; // ms elapsed since last update
 remaining -= elapsed; // adjust remaining time
 lastUpdate = now; // remember this update time

 // Convert remaining milliseconds to mm:ss format and display
 if (remaining < 0) remaining = 0;
 int minutes = (int)(remaining/60000);
 int seconds = (int)((remaining)/1000);


 label.setText(format.format(minutes) + ":" + format.format(seconds));
 label.setForeground(new Color(251,251,254));
    label.setBackground(new Color(0,0,0));
 // If we've completed the countdown beep and display new page
 if (remaining == 0) {
     // Stop updating now.
     timer.stop();
 }

     count.add(label);

Puzframe.add(label,BorderLayout.SOUTH); }

这是我到目前为止所拥有的,但我的问题是它没有出现在我的游戏中。我正在从 actionPerformed 调用 updateDisplay()

最佳答案

使用 Swing Timer它就是为这样的场景而设计的

//javax.swing.Timer
 timer = new Timer(4000, new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
     JOptionPane.showMessageDialog(mainFrame,
             "End Of Game",
             "5 minutes has passed",
             JOptionPane.ERROR_MESSAGE);
   }
 });

我准备了一个简单的例子来演示它

示例

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

public class SwingControlDemo {

   private JFrame mainFrame;
   private JPanel controlPanel;
   private Timer timer;

  public SwingControlDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingControlDemo swingControlDemo = new SwingControlDemo();  
      swingControlDemo.showEventDemo();       
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
           System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(controlPanel);
      mainFrame.setVisible(true);

     //javax.swing.Timer
     timer = new Timer(4000, new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {
         JOptionPane.showMessageDialog(mainFrame,
                 "End Of Game",
                 "5 minutes has passed",
                 JOptionPane.ERROR_MESSAGE);
       }
     });
   }

   private void showEventDemo(){

      JButton okButton = new JButton("Start Game");

      okButton.setActionCommand("OK");

      okButton.addActionListener(new ButtonClickListener()); 

      controlPanel.add(okButton);

      mainFrame.setVisible(true);  
   }

   private class ButtonClickListener implements ActionListener{

      public void actionPerformed(ActionEvent e) {
        timer.start();
         String command = e.getActionCommand();  
         if( command.equals( "OK" ))  {
           System.out.println("Timer started");
         }
      }
   }
}

关于java - 倒数计时器帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37463690/

相关文章:

java - 使用Java代码或数据库功能插入随机帐号?

linux - 自动递归接触当前目录中的所有内容

java applet 无法打印 actionPerformed 中的值

java - 当表中的数据更新时,选定的行将被清除

java - 使用 RFC3696 进行电子邮件验证(电子邮件地址)

java - JSP无法删除FILE

ios - 将按钮连接到计时器并以百分比计算时间

java - 以给定的执行时间启动线程

java - 我必须从主类中调用小程序吗?

java - java小程序中的.class错误