Implementing the UI classes

ImageCanvas class

This class displays the selected image on the screen. The image is drawn with its original dimensions and no attempt is made to scale it if it does not fit the screen.

ImageCanvas listens for user input for purposes of returning the control back to the MIDlet.

To create this class:

  1. Create the ImageCanvas.java class file.

  2. Import the required packages.

    import java.io.*;
    import javax.microedition.io.*;
    import javax.microedition.io.file.*;
    import javax.microedition.lcdui.*;
  3. Set the ImageCanvas class to extend the Canvas class and implement the CommandListener interface. Define the global variables and the ImageCanvas constructor.

    class ImageCanvas
            extends Canvas implements CommandListener {
    
        private final ImageViewerMIDlet midlet;
        private static final int CHUNK_SIZE = 0;
        private Image currentImage = null;
        int imageWidth;
        int imageHeight;
        private Command backCommand = new Command("Back", Command.BACK, 0);
        private Ticker ticker = new Ticker("Image Viewer");
        private int mouseDownX;
        private int mouseDownY;
        private int deltaX;
        private int deltaY;
        private int posX;
        private int posY;
    
        ImageCanvas(ImageViewerMIDlet midlet) {
            setTitle("Image Viewer");
            this.midlet = midlet;
            this.addCommand(backCommand);
            this.setCommandListener(this);
            this.setTicker(ticker);
        }
  4. Use the displayImage method to display the selected image on the screen.

    To access the device file system, load the image into memory, and display the image on the screen, create a FileConnection. After the image is no longer needed, call the Connection.close method to close the FileConnection. Calling the close method is important for ensuring that the image becomes available for other applications.

        public boolean displayImage(String imgName) {
            try {
                FileConnection fileConn =
                        (FileConnection) Connector.open(imgName, Connector.READ);
    
                InputStream fis = fileConn.openInputStream();
                int overallSize = (int) fileConn.fileSize();
    
                byte[] imageData = new byte[overallSize];
    
                int readAmount = fis.read(imageData, 0, overallSize);
    
                fis.close();
                fileConn.close();
                ticker.setString("Image Viewer:" + imgName);
                currentImage = Image.createImage(imageData, 0, overallSize);
                fis.close();
                fileConn.close();
                imageWidth = currentImage.getWidth();
                imageHeight = currentImage.getHeight();
                repaint();
            } catch (IOException e) {
                midlet.showError(e);
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                midlet.showError(e);
                return false;
            } catch (Error e) {
                e.printStackTrace();
                if (e instanceof OutOfMemoryError) {
                    midlet.showError("File is too large to display");
                } else {
                    midlet.showError("Failed to display this file. " + e.getMessage());
                }
                return false;
            }
            return true;
        }
    
        protected void paint(Graphics g) {
            int w = getWidth();
            int h = getHeight();
    
            // Set background color to black
            g.setColor(0x00000000);
            g.fillRect(0, 0, w, h);
    
            setImagePlacementPoint();
    
            System.out.println("Pos X:" + posX + " Y:" + posY);
    
            if (currentImage != null) {
                g.drawImage(currentImage,
                        posX,
                        posY,
                        Graphics.HCENTER | Graphics.VCENTER);
            } else {
                // If no image is available display a message
                g.setColor(0x00FFFFFF);
                g.drawString("No image",
                        posX,
                        posY,
                        Graphics.HCENTER | Graphics.BASELINE);
            }
        }
    
        protected void keyReleased(int keyCode) {
            // Exit with any key
            midlet.displayFileBrowser();
        }
    
        public void commandAction(Command command, Displayable displayable) {
            if (command == backCommand) {
                currentImage = null;
                midlet.displayFileBrowser();
            }
        }
    
        protected void pointerPressed(int x, int y) {
            mouseDownX = x;
            mouseDownY = y;
        }
    
        protected void pointerReleased(int x, int y) {
            deltaX = 0;
            deltaY = 0;
            System.out.println("up up up !");
        }
    
        protected void pointerDragged(int x, int y) {
            deltaX = x - mouseDownX;
            deltaY = y - mouseDownY;
            mouseDownX = x;
            mouseDownY = y;
            repaint();
        }
    
        void setImagePlacementPoint() {
    
            // This needs to be taken each time, since the values will be chaged when
            // user tilt the phone to potrait mode to landscape mode.
            int canvasWidth = getWidth();
            int canvasHeight = getHeight();
    
            if (imageWidth > canvasWidth && deltaX != 0) {
                posX += deltaX;
                if (posX < (canvasWidth - imageWidth / 2)) {
                    posX = canvasWidth - imageWidth / 2;
                } else if (posX > (imageWidth / 2)) {
                    posX = (imageWidth / 2);
                }
            } else {
                posX = canvasWidth / 2;
            }
    
            if (imageHeight > canvasHeight && deltaY != 0) {
                posY += deltaY;
                if (posY < (canvasHeight - imageHeight / 2)) {
                    posY = canvasHeight - imageHeight / 2;
                } else if (posY > (imageHeight / 2)) {
                    posY = (imageHeight / 2);
                }
            } else {
                posY = canvasHeight / 2;
            }
        }
    }

InputScreen class

This class is a simple Form used for prompting the user to enter text. This is used when creating a new directory or when renaming a file.

InputScreen creates an input text field and returns the input results to the MIDlet.

To create this class:

  1. Create the InputScreen.java class file.

  2. Import the required packages.

    import javax.microedition.lcdui.*;
  3. Implement the InputScreen class.

    class InputScreen extends Form implements CommandListener
    {
      private final ImageViewerMIDlet midlet;
      private final TextField inputField =
            new TextField("Input", "", 32, TextField.ANY);
      private final Command okCommand =
            new Command("OK", Command.OK, 1);
      private final Command cancelCommand =
            new Command("Cancel", Command.OK, 1);
    
    
      InputScreen(ImageViewerMIDlet midlet)
      {
        super("Input");
        this.midlet = midlet;
        append(inputField);
        addCommand(okCommand);
        addCommand(cancelCommand);
        setCommandListener(this);
      }
    
    
      public void setQuestion(String question, String text)
      {
        inputField.setLabel(question);
        inputField.setString(text);
      }
    
    
      public String getInputText()
      {
        return inputField.getString();
      }
    
    
      public void commandAction(Command command, Displayable d)
      {
        if (command == okCommand)
        {
          midlet.input(inputField.getString());
        }
        else if (command == cancelCommand)
        {
          midlet.cancelInput();
        }
      }
    
    }

ErrorScreen class

This class is used for reporting runtime errors to the user.

To create this class:

  1. Create the ErrorScreen.java class file.

  2. Import the required packages.

    import javax.microedition.lcdui.*;
  3. Implement the ErrorScreen class.

    class ErrorScreen
      extends Alert
    {
      private static Image image;
      private static Display display;
      private static ErrorScreen instance = null;
    
    
      private ErrorScreen()
      {
        super("Error");
        setType(AlertType.ERROR);
        setTimeout(5000);
        setImage(image);
      }
    
    
      static void init(Image img, Display disp)
      {
        image = img;
        display = disp;
      }
    
    
      static void showError(String message, Displayable next)
      {
        if (instance == null)
        {
          instance = new ErrorScreen();
        }
        instance.setTitle("Error");
        instance.setString(message);
        display.setCurrent(instance, next);
      }
    
    }

The Image Viewer MIDlet has been created. You can now build it and test it in an emulator and then deploy it to a device.