Java Help Please. Trouble getting two Class Files Working.

Soldato
Joined
12 Sep 2003
Posts
10,780
Location
Newcastle, UK
Hi all. I've been following a Tutorial to create a StopWatch Application (MIDlet). However, I've had to adapt it and I have 3 errors which I can't seem to fix.

One class file should bring up the menu ("STOPWATCH"), which when the option is selected, loads the other class file ("STOPWATCHDISPLAY") which shows the Application.

The only problem in this first file was the following line:-

Code:
Display.getDisplay(StopWatch.instance).setCurrent(StopWatchDisplay);

It said Cannot Find Symbol... Symbol = Variable "StopWatchDisplay" and also Variable "Instance". Both from the same line.

which I have changed to now:-

Code:
Display.getDisplay().setCurrent(StopWatchDisplay());

This then made me import "StopWatchDisplay" shown at the start of the code below. This is now giving me ONE error for this file.

'.' expected. :confused:


Here is the full code from the "MENU" interface (StopWatch):-

Code:
//package stopwatch2;

import StopWatchDisplay;
import java.io.*;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;

public class StopWatch extends MIDlet implements CommandListener 
{
    public StopWatch ()
    {
     initialize();
    }
   
    private List list1;
    private Form form2;
    private Command backCommand1;
    private Command cancelCommand1;
    private Command connect = new Command("Connect", Command.SCREEN, 1);
    private TextField tb;
    
     /** Called by the system to indicate that a command has been invoked on a particular displayable.
     * @param command the Command that ws invoked
     * @param displayable the Displayable on which the command was invoked
     */

    public void commandAction(Command command, Displayable displayable) 
    {
        if (displayable == list1) 
        {
          if (command == cancelCommand1) 
          {
            exitMIDlet();
          } 

            else if (command == list1.SELECT_COMMAND) 
            {
              switch (get_list1().getSelectedIndex()) 
              {
                case 0:
                getDisplay().setCurrent(get_form2());
                break;
              }
            }
         } 
        
         else if (displayable == form2) 
         {
           if (command == backCommand1) 
           {
             getDisplay().setCurrent(get_list1());
           }
           
           if (command == connect) 
           {
             // Show the StopWatchDisplay screen.
             Display.getDisplay().setCurrent(StopWatchDisplay());
           }

          } 
      }
    
    
    /*This method initializes UI of the application.*/

    private void initialize() 
    {
      getDisplay().setCurrent(get_list1());
    }
    
    /*This method should return an instance of the display.*/

    public Display getDisplay() 
    {               
      return Display.getDisplay(this);
    }                        
    
    /*This method should exit the midlet.*/

    public void exitMIDlet() 
    {              
      getDisplay().setCurrent(null);
      destroyApp(true);
      notifyDestroyed();
    }   
    
    //Create the List (Menu)
    public List get_list1() 
    {
      if (list1 == null) 
      {
        list1 = new List(null, Choice.IMPLICIT, new String[] 
        {
          "1. Start Stopwatch",
        }, new Image[] 
        
        {
          null
        });

        list1.addCommand(get_cancelCommand1());
        list1.setCommandListener(this);
        list1.setSelectedFlags(new boolean[] 
        {
          false
        });

       }
       return list1;
     }
    
    //Create the Cancel Command.
    public Command get_cancelCommand1() 
    {
      if (cancelCommand1 == null) 
      {
        cancelCommand1 = new Command("Cancel", Command.CANCEL, 1);
      }
      return cancelCommand1;
    }
    
    //Create the Form.  Once the Option is Selected this form is displayed.
    public Form get_form2() 
    {
      if (form2 == null) 
      {
        form2 = new Form("Connect to the StopWatch");
        tb = new TextField("Please click Connect below: ","",30,TextField.ANY);
        
        form2.append(tb);
        form2.addCommand(get_backCommand1());
	form2.addCommand(connect);
        form2.setCommandListener(this);
       }
       return form2;
     }
    
    //Create the Back Command.
    public Command get_backCommand1() 
    {
      if (backCommand1 == null) 
      {
        backCommand1 = new Command("Back", Command.BACK, 1);
      }
      return backCommand1;
    }
    
    public void startApp() 
    {
    }
    
    public void pauseApp() 
    {
    }
    
    public void destroyApp(boolean unconditional) 
    {
    }

}


The second class file did have this error:-

Similar to the first error,

Code:
Display.getDisplay(StopWatchDisplay.instance).setCurrent(StopWatch);

Cannot Find Symbol... Symbol = Variable "Instance"

However, I changed it to:-

Code:
Display.getDisplay(StopWatch);

This seems to have worked, and cleared all the errors from this class file.

Here is the complete code for "StopWatchDisplay":-

Code:
//package stopwatch2;

import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

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

  
   /**
   * 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 (StopWatch).
   */
  
  public StopWatchDisplay(StopWatch StopWatch) 
  {
    // Save the StopWatch instance so that we can access it later when we
    // want to switch back to the StopWatch (Menu) screen.
    this.StopWatch = StopWatch;

    // Initialize the canvas.
    try 
    {
      jbInit();
    }
    catch(Exception e) 
    {
      e.printStackTrace();
    }
  }
  
   /**
   * Component initialisation.  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));
  }
  
   /*Handle command events.*/
  public void commandAction(Command command, Displayable displayable) 
  {
    // 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 (StopWatch) screen.
          Display.getDisplay(StopWatch);
        }
 }
  
   /*Releases references.  Used when quitting the MIDlet.*/
  void destroy() 
  {
    timer            = null;
    runStopWatchTask = null;
    startCommand     = null;
    stopCommand      = null;
  }

    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);
    }
    
   /**
   * Formats the given number of milliseconds into minute/seconds/tenths
   * display.  For instance, 2346 milliseconds will translate to 00:02:4.
   * @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 ":".
   return minuteString + ":" + secondsString + ":" + String.valueOf(tenths);
    }
    
}
  
  /*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);
    }
  }
  
  /**
   * 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();
    }
  }
}

Now it looks to me as if it just doesn't know about the other class, I'm not too sure. Tbh I've cut and took bits from other pieces of work it's a bit of a mess. But even with all that, there are only a few errors, which I can't seem to sort out. Declaration problem? :(

Thanks for any help.
 
Last edited:
*UPDATE*

Think I solved the Variable issue regarding the Class "StopWatch" by removing the line at the beginning saying,

Code:
package stopwatch2;

Still need help with the Display part, I'm not sure on how the wording goes for that bit. :)

EDIT: Updated first post to remove un-needed stuff.
 
Back
Top Bottom