⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stopwatchdisplay.java

📁 J2ME平台上经典的stoSwatch系统。系统架构清晰
💻 JAVA
字号:
package stopwatch;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.*;

public class StopWatchDisplay extends Canvas implements CommandListener {

  // Timer for running the stopwatch task
  private Timer timer;
  // Stopwatch running task
  private RunStopWatch runStopWatchTask;
  // Stopwatch start time
  private long startTime    = 0;
  // Canvas width
  private int width = getWidth();
  // Canvas height
  private int height = getHeight();
  // Font for drawing the stopwatch time
  private Font font = Font.getDefaultFont();
  // Command for starting the stopwatch
  private Command startCommand = new Command("Start", Command.SCREEN, 1);
  // Command for stopping the stopwatch
  private Command  stopCommand  = new Command("Stop", Command.SCREEN, 1);
  // Main menu.
  private MainMenu mainMenu;


/*
  public StopWatchDisplay() {
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
*/

/**
 * Constructs a new StopWatchDisplay canvas for drawing the stopwatch,
 * starting and stopping the stopwatch, and provides an option to go back
 * to the given MainMenu instance.
 *
 * @param mainMenu  parent MainMenu screen instance
 */
public StopWatchDisplay(MainMenu mainMenu) {
  // Save the MainMenu instance so that we can access it later when we
  // want to switch back to the MainMenu screen.
  this.mainMenu = mainMenu;

  // Initialize the canvas.
  try {
    jbInit();
  }
  catch(Exception e) {
    e.printStackTrace();
  }
}

/*
  private void jbInit() throws Exception {
    // Set up this Displayable to listen to command events
    setCommandListener(this);
    // add the Exit command
    addCommand(new Command("Exit", Command.EXIT, 1));
  }
 */
/**
 * Component initialization.  Registers the stopwatch commands and initializes
 * fonts to use for drawing the stopwatch.
 */
private void jbInit() throws Exception {
  // Add the "Start" command for starting the stopwatch.  Later, after
  // the user hits "start", we will swap this command for the "Stop"
  // command.
  addCommand(startCommand);

  // Initialize the font that we will use to draw the stopwatch time
  // onto the canvas.
  initializeFont();

  // Set up this Displayable to listen to command events.
  setCommandListener(this);

  // Add the command for exiting the MIDlet.
  addCommand(new Command("Back", Command.BACK, 1));
}


  public void commandAction(Command command, Displayable displayable) {
    /** @todo Add command handling code */
    // Get the command type
    int commandType = command.getCommandType();
    // Check if the command received was one that we defined (as opposed
    // to an EXIT command or a MIDlet STOP command.
    if (commandType == Command.SCREEN) {

      // Get the string label associated with the command.
      String commandName = command.getLabel();
      // Now check if the string label matches either our Start or Stop
      // commands.
      if (commandName.equals("Start")) {

        // Someone has pressed the Start button, so...

        // Get our current time.
        startTime        = System.currentTimeMillis();

       // Create a new Timer to run the stopwatch.
        timer            = new Timer();

        // Create a new RunStopWatch task to give to the timer.
        runStopWatchTask = new RunStopWatch();

        // Ask the Timer to run the stopwatch.
        // The task to run.
        timer.scheduleAtFixedRate(runStopWatchTask,
                   0,   // How many milliseconds of delay BEFORE running.
                   10); // Time in milliseconds between successive task executions,
                        // (i.e. run it every 10 milliseconds).

        // Now, swap the Start command for the Stop command so that the
        // user can stop the stopwatch!
        removeCommand(startCommand);
        addCommand(stopCommand);
      }

      else if (commandName.equals("Stop")) {
        // Someone has pressed the Stop button.
        timer.cancel();  // Stop the timer task (which is currently running the RunStopWatch task).
        timer = null;    // Set it explicitly to null to make sure that the timer has been reset.

        // Swap the Stop command for the Start command so that the user can
        // start the stopwatch again.
        removeCommand(stopCommand);
        addCommand(startCommand);
      }
    }
    else if (commandType == Command.BACK) {
      // Go back to the Main Menu screen.
      Display.getDisplay(StopWatch.instance).setCurrent(mainMenu);
    }

  }



  protected void paint(Graphics g) {
    // "Clear" the Canvas by painting the background white (you may choose
     // another color if you like.
     // Set the current pen color to white (red=255, green=255, blue=255).
     g.setColor(255, 255, 255);
     // Fill the entire canvas area with the current pen color.
     g.fillRect(0, 0, width, height);

     // Find out what is the current stopwatch time.  The stopwatch time is
     // the current time MINUS the startTime that was recorded when the
     // user pressed the Start button.  If the startTime is 0, then the
     // current stopwatch time is 0 as well.
     long elapsed = (startTime == 0)
                      ? 0
                      : System.currentTimeMillis() - startTime;

     // Set the pen to black (it's currently white).
     g.setColor(0);

     // Set a font to use for drawing the time. (see the method initializeFont())
     g.setFont(font);

     // Dynamically compute the best position to draw the stopwatch string given
     // the width and height of your canvas.
     // For instance, to center the text on ANY canvas:
     //   x position = (canvaswidth / 2) - (stopwatchstringlength / 2)
     //   y position = (canvasheight / 2) - (stopwatchstringheight / 2)

     // Formats the current time into MM:SS:T format.
     String formattedTime = formatTime(elapsed);

     // Compute the start point of our text such that it will be centered
     // on our canvas.
     int x = (width / 2) - (font.stringWidth(formattedTime) / 2);
     int y = (height / 2) - (font.getHeight() / 2);

     // Now draw the string at the (x, y) anchor point that we just computed.
     // Specify that we want the anchor point to be the top left corner of our
     // text.
     g.drawString(formattedTime, x, y, Graphics.TOP | Graphics.LEFT);

  }
  /**
   * <p>Formats the given number of milliseconds into minute/seconds/tenths
   * display.  For instance, 2346 milliseconds will translate to 00:02:4.</p>
   *
   * @param milliseconds number of milliseconds
   * @return string in the form of "MM:SS:T"
   */
  private String formatTime(long milliseconds) {
    long minutes = 0;                          // Start with 0 minutes.
    long seconds = milliseconds / 1000;        // Get the number of seconds.
    long tenths  = (milliseconds / 100) % 10;  // Number of tenths of seconds.

    // Check how many seconds we have.
    if (seconds >= 60) {
      // If we have more than 60 seconds, we can break it down into minutes.
      minutes = seconds / 60;  // Get the number of minutes.
      seconds = seconds % 60;  // Get the number of remainder seconds.
    }

    // Create our "minutes" string.
    String minuteString = String.valueOf(minutes);
    if (minutes > 10) {
      // We have less than 10 minutes, so prepend a "0" to make sure.
      // Our minutes string has 2 digits.
      minuteString = "0" + minuteString;
    }

    // Create our "seconds" string
    String secondsString = String.valueOf(seconds);
    if (seconds > 10) {
      // We have less than 10 seconds, so prepend a "0" to make.
      // Sure our seconds string has 2 digits.
      secondsString = "0" + secondsString;
    }

    //Put together and return a String of minutes, seconds, and tenths of
    //seconds, each separated by a ":".
    String resultString = minuteString + ":" + secondsString;
    if (mainMenu.getDisplayFormat() == Options.FORMAT_TENTHS) {
      // User has indicated that the tenths of seconds should be displayed.
      // Add it to our result string.
      resultString += ":" + String.valueOf(tenths);
    }
    return resultString;


  }

  /**
   * Initialize the font to the largest possible that can fit the display area.
   */
  private void initializeFont() {
   // Test the font with this string to see if the string
    // will fit on the canvas.
    String test = "00:00:0";

    // See how many of the test strings we can fit on the screen with
    // the default font.
    int  numStringsForThisWidth = width / font.stringWidth(test);

    if (width / numStringsForThisWidth > 2) {
      // More than 2 strings can fit across our canvas using the current font.
      // Set the font to one size bigger.
      font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_LARGE);
    }

    else if (numStringsForThisWidth == 0) {
      // Our test string does NOT fit on the canvas with the current font.  Set
      // the font to one size smaller.
      font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_SMALL);
    }
  }


  /**
   * <p>Releases references.  Used when quitting the MIDlet.</p>
   */
  void destroy() {
    timer            = null;
    runStopWatchTask = null;
    startCommand     = null;
    stopCommand      = null;
  }

  /**
    * This inner class is the task to give the timer when the user starts the
    * stopwatch.  This task will run at the interval specified by the timer.
    * (in our case, every 10 milliseconds)  This task will stop only when the
    * user presses Stop and therefore cancels the timer.
    */
   class RunStopWatch extends TimerTask {
     public void run() {
       // Repaint() automatically calls paint().
       StopWatchDisplay.this.repaint();
     }
   }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -