0% found this document useful (0 votes)
10 views18 pages

IMAD Unit 4 Notes

Introduction to mobile application development, helpful for students

Uploaded by

omverma1234q
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views18 pages

IMAD Unit 4 Notes

Introduction to mobile application development, helpful for students

Uploaded by

omverma1234q
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT 4

High-Level Display Screens in J2ME: Screen Class and Alert Class

In J2ME (Java 2 Micro Edition), the user interface (UI) is primarily built using Displayable
objects. These objects represent various types of screens that can be shown on a mobile
device, such as forms, lists, and canvases. For more specialized purposes, J2ME provides
high-level display screens like Screen (abstract base class) and Alert that help developers
manage the presentation and interaction with users on mobile devices.

Let's dive deeper into the Screen and Alert classes in J2ME:

Screen Class in J2ME

The Screen class in J2ME is an abstract class that serves as the base for all types of
Displayable objects. Specifically, Screen represents any visual element that can be displayed
to the user on the screen.

Key Points:

 The Screen class is abstract, meaning it cannot be instantiated directly. Instead, it is


subclassed by concrete classes like Form, Canvas, and List.
 It provides basic functionality to manage how content is displayed and interacted with
by the user.
 Most UI components in J2ME derive from the Screen class, and you interact with
these screens using the Display class, which sets the current screen (or Displayable
object) to be shown.

Common Subclasses of Screen:

1. Form: A screen used to collect and display data in various input fields, such as text
fields and commands.
2. Canvas: A low-level screen that allows for custom graphics, drawing, and handling
complex input events like touch and key presses.
3. List: A screen that displays a list of items from which the user can choose.

Methods in Screen:

Some key methods of the Screen class (inherited by all subclasses) include:

 setCommandListener(CommandListener l): Registers a command listener to


receive command events for this screen.
 addCommand(Command c): Adds a command to the screen. Commands are typically
linked to user actions like pressing buttons or selecting menu items.
 setCurrent(Displayable d): This method is used to switch between different
screens and make the current screen visible.
Example Usage of Screen (Form and List):

import javax.microedition.lcdui.*;

public class MyMIDlet extends MIDlet implements CommandListener {

private Display display;


private Form form;
private Command exitCommand;

public MyMIDlet() {
display = Display.getDisplay(this);
form = new Form("User Input Form");

// Create an exit command


exitCommand = new Command("Exit", Command.EXIT, 1);
form.addCommand(exitCommand);

// Set command listener


form.setCommandListener(this);
}

public void startApp() {


display.setCurrent(form); // Display the form
}

public void commandAction(Command c, Displayable d) {


if (c == exitCommand) {
notifyDestroyed(); // Exit the application
}
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
}
In this example, we create a Form (a subclass of Screen), add an Exit command, and set up a
CommandListener to handle user input.

Alert Class in J2ME

The Alert class in J2ME is a specific type of Displayable that is used to display temporary
pop-up messages or notifications to the user. Alerts are typically used for informing the user
about an event or error, such as a successful operation, an error, or a warning.

Key Features of Alert Class:

 Type of Information: Alerts can be created with different AlertTypes, such as INFO,
WARNING, ERROR, or CONFIRM, which visually differentiate the severity or type of the
message being displayed.
 Timeout: Alerts can automatically disappear after a certain period or can stay visible
until the user dismisses them.
 Content: You can add text, images, and sound to an alert to make it more informative
or interactive.

Constructor of Alert Class:

java
Copy code
public Alert(String title, String text, Image image, AlertType type)

 title: The title of the alert (shown at the top of the alert box).
 text: The content of the alert message.
 image: An optional image displayed with the alert.
 type: The type of the alert, which affects its appearance. Common types include:
o AlertType.INFO: Informational alert (green icon).
o AlertType.WARNING: Warning alert (yellow icon).
o AlertType.ERROR: Error alert (red icon).
o AlertType.CONFIRM: Confirmation alert (blue icon).

Setting Timeout for Alerts:

You can also set how long an alert should be visible using setTimeout(int timeout):

 A timeout value of Alert.FOREVER will make the alert stay on screen until dismissed
by the user.
 Any other positive integer represents the timeout in milliseconds.
Example Usage of Alert Class:

import javax.microedition.lcdui.*;

public class MyMIDlet extends MIDlet {

private Display display;


private Form form;
private Command exitCommand;

public MyMIDlet() {
display = Display.getDisplay(this);
form = new Form("Main Form");

exitCommand = new Command("Exit", Command.EXIT, 1);


form.addCommand(exitCommand);
form.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
showAlert(); // Show an alert before exiting
}
}
});
}

public void startApp() {


display.setCurrent(form);
}

public void showAlert() {


// Create an info alert with some text
Alert alert = new Alert("Info", "Exiting application!", null, AlertType.INFO);

// Set the alert to stay for 2 seconds


alert.setTimeout(2000); // Timeout in milliseconds

// Show the alert


display.setCurrent(alert, form); // Show the alert followed by the form
}

public void pauseApp() {}


public void destroyApp(boolean unconditional) {}
}

In this example, we create an Alert to inform the user that the application is exiting. After
displaying the alert for a brief period (2 seconds), the alert will automatically disappear.

Alert Types:

 AlertType.INFO: Used for general information messages, such as success messages


or notifications.
 AlertType.WARNING: Used for warnings, typically indicating that something may
require the user's attention but is not a critical issue.
 AlertType.ERROR: Used for error messages, typically indicating that something went
wrong in the application.
 AlertType.CONFIRM: Used when you need a confirmation from the user before
proceeding (e.g., "Are you sure you want to delete this item?").

Differences Between Form, List, and Canvas:

While the Screen class is an abstract base class, here are some distinctions between its
common subclasses:

1. Form:
o A container for UI components such as TextField, ChoiceGroup, TextBox,
etc.
o Best suited for collecting user input and displaying forms with fields.
2. List:
o Used for displaying a list of items, where each item can be selected by the
user.
o Typically used for menus, lists, or other select-able collections of items.
3. Canvas:
o A low-level UI component that allows for custom graphics, drawing, and more
complex event handling (e.g., touch input or key events).

Ideal for games or applications requiring custom graphics or gestures. Form Class in
J2ME

The Form class in J2ME is a Displayable that provides a container for user interface
components (like Items) on a screen. It is typically used for gathering user input, displaying
data, and organizing UI elements into a structured format.

Key Features of Form Class:

 Container for Items: A Form holds Items (like text fields, choice groups, and
buttons) and organizes them in a layout.
 Commands: A Form can have commands like "OK", "Cancel", "Exit", and custom
commands added to it.
 Displayable: Being a subclass of Displayable, a Form is part of the user interface
and can be set as the current screen using Display.setCurrent().

Important Methods in Form:

 append(Item item): Adds an item (e.g., TextField, ChoiceGroup, etc.) to the form.
 setCommandListener(CommandListener l): Sets a CommandListener to handle
user commands like pressing buttons or selecting items.
 addCommand(Command c): Adds a command to the form, such as "Submit" or "Exit".
 delete(Item item): Removes an item from the form.
 insert(int index, Item item): Inserts an item at a specific index in the form.
 setTitle(String title): Sets the title of the form (typically displayed at the top of
the form).

Example:

import javax.microedition.lcdui.*;

public class MyMIDlet extends MIDlet implements CommandListener {

private Display display;

private Form form;

private Command exitCommand;

public MyMIDlet() {

display = Display.getDisplay(this);

form = new Form("User Input");


// Create a command

exitCommand = new Command("Exit", Command.EXIT, 1);

form.addCommand(exitCommand);

// Set command listener

form.setCommandListener(this);

public void startApp() {

display.setCurrent(form);

public void commandAction(Command c, Displayable d) {

if (c == exitCommand) {

notifyDestroyed(); // Exit the app

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

Item Class in J2ME

The Item class is an abstract base class in J2ME used to represent user interface components
that can be placed on a Form. All items (like buttons, text fields, and choice groups) derive
from the Item class. It provides basic functionality for managing labels, values, and state.

Key Features of Item Class:

 Abstract Class: You cannot instantiate the Item class directly. Instead, you use its
subclasses such as TextField, ChoiceGroup, DateField, etc.
 State Change Handling: You can add listeners to items to handle state changes (e.g.,
when a user enters text or selects a choice).
 Label and Value: Items can have a label (text displayed next to them) and a value
(the content or user input associated with the item).
Common Subclasses of Item:

 TextField: Used to display and collect single-line text input from the user.
 ChoiceGroup: A group of selectable items (e.g., a set of radio buttons or checkboxes).
 DateField: Allows the user to select a date.
 TextBox: Used to display and collect multi-line text input.

Example with Item Subclasses:

import javax.microedition.lcdui.*;

public class MyMIDlet extends MIDlet {

private Display display;

private Form form;

private TextField nameField;

private ChoiceGroup choiceGroup;

public MyMIDlet() {

display = Display.getDisplay(this);

form = new Form("User Input");

// Create a TextField item

nameField = new TextField("Name:", "", 30, TextField.ANY);

form.append(nameField);

// Create a ChoiceGroup item (radio buttons)

choiceGroup = new ChoiceGroup("Gender:", ChoiceGroup.EXCLUSIVE);

choiceGroup.append("Male", null);

choiceGroup.append("Female", null);

form.append(choiceGroup);

public void startApp() {

display.setCurrent(form);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

List Class in J2ME

The List class in J2ME is a subclass of Displayable that displays a list of items for the user
to select from. It can be used for displaying menus, options, or any list-based UI elements.

Key Features of List Class:

 Selectable Items: Each item in the list can be selected by the user, either by tapping
or using the device's navigation keys.
 Types of Lists: There are two main types of lists:
o Choice.IMPLICIT: No item is selected by default. The user can choose one
item.
o Choice.EXCLUSIVE: A single item can be selected from the list, similar to a
set of radio buttons.
o Choice.MULTIPLE: Multiple items can be selected, similar to checkboxes.
 Commands: Like other Displayable objects, a List can have commands (e.g.,
"OK", "Cancel").

Important Methods in List:

 append(String label, Image image): Adds an item to the list with a label and an
optional image.
 getSelectedIndex(): Returns the index of the currently selected item.
 setCommandListener(CommandListener l): Sets the listener to handle command
events.

Example:

import javax.microedition.lcdui.*;

public class MyMIDlet extends MIDlet implements CommandListener {


private Display display;
private List list;
private Command exitCommand;
public MyMIDlet() {
display = Display.getDisplay(this);
list = new List("Choose an Option", List.IMPLICIT);
// Add items to the list
list.append("Option 1", null);
list.append("Option 2", null);
// Create and add a command to the list
exitCommand = new Command("Exit", Command.EXIT, 1);
list.addCommand(exitCommand);
list.setCommandListener(this);
}
public void startApp() {
display.setCurrent(list); // Show the list
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
notifyDestroyed(); // Exit the app
}
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
}

TextBox Class in J2ME

The TextBox class in J2ME is a subclass of Item used for multi-line text input, making it
more suitable for collecting longer input from the user (e.g., comments or messages). Unlike
TextField, which is for single-line text, TextBox is more flexible and can display and collect
multiple lines of text.

Key Features of TextBox Class:

 Multi-line Input: It allows the user to enter multiple lines of text, making it ideal for
longer inputs.
 Text Type: It can be used for plain text or email, URL, or password entry (depending
on the TextBox type).
 Input Constraints: You can set constraints on the input (e.g., a TextBox for email
may only allow valid email formats).
Important Methods in TextBox:

 setString(String str): Sets the text in the TextBox.


 getString(): Gets the text entered by the user.
 setConstraints(int constraints): Sets input constraints (e.g., numeric only,
email format).

Example:

import javax.microedition.lcdui.*;

public class MyMIDlet extends MIDlet {


private Display display;
private TextBox textBox;
private Command okCommand;

public MyMIDlet() {
display = Display.getDisplay(this);
textBox = new TextBox("Enter Message", "", 200, TextField.ANY);

// Create and add a command


okCommand = new Command("OK", Command.OK, 1);
textBox.addCommand(okCommand);
textBox.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c == okCommand) {
String inputText = textBox.getString();
System.out.println("User entered: " + inputText);
}
}
});
}
Ticker Class in J2ME

The Ticker class in J2ME allows you to display scrolling text or a ticker message at the top
or bottom of a screen (like a news ticker or scrolling notification). It is often used for
providing brief updates or information that needs to be continuously visible.

Key Features of Ticker Class:

 Scrolling Text: Displays text that can automatically scroll across the screen.
 Position: A Ticker is typically displayed on the title area of a Form or any
Displayable screen.

Example:

import javax.microedition.lcdui.*;

public class MyMIDlet extends MIDlet {


private Display display;
private Form form;
private Ticker ticker;

public MyMIDlet() {
display = Display.getDisplay(this);
form = new Form("Ticker Example");

// Create a ticker with a scrolling message


ticker = new Ticker("This is a scrolling ticker message!");

// Set the ticker on the form


form.setTicker(ticker);
}

public void startApp() {


display.setCurrent(form); // Display the form with ticker
}
public void pauseApp() {}

public void destroyApp(boolean unconditional) {}


}
In this example, a Ticker is created and displayed on top of the form, showing a scrolling message.

ow-Level Display Canvas in J2ME

In J2ME (Java 2 Micro Edition), the Canvas class is a low-level, flexible screen component
that allows for custom rendering and user interaction handling. Unlike higher-level
Displayable components (like Form or List), the Canvas class gives developers full control
over the screen's drawing and input, making it ideal for games, drawing applications, or any
app that requires custom graphics or animations.

Here’s an overview of the Canvas class and its associated concepts, such as user
interactions, graphics, clipping regions, and animation.

The Canvas Class

The Canvas class is used when you need to manage custom graphics and more advanced user
interactions (like touch, pointer, and key events). It is subclassed to create specific canvases
for applications, often seen in games and graphical apps.

Key Features of Canvas:

 Custom Drawing: You can override the paint(Graphics g) method to render


custom images, shapes, or text.
 Event Handling: Canvas allows handling various input events such as key presses,
pointer touch (stylus or finger), and joystick movements (on devices with such input
methods).
 Full Control: Developers can control the screen’s rendering process, including
drawing primitives (lines, shapes), images, and text.
 Graphics Object: The Canvas provides a Graphics object that allows low-level
drawing operations.

Common Methods in Canvas:

 paint(Graphics g): The method you override to handle custom drawing on the
canvas. This method is called when the canvas is rendered or needs to be refreshed.
 getGraphics(): Returns the Graphics object used to draw on the canvas.
 serviceRepaints(): Requests a repaint of the canvas. This can be used to update the
screen in a controlled manner.
 keyPressed(int keyCode): Handles key presses from the user.
 pointerPressed(int x, int y): Handles pointer events, such as when the user
taps on the canvas.
 setFullScreenMode(boolean fullScreen): This method allows you to toggle full-
screen mode for the canvas.

Creating a Simple Canvas:

Here’s a simple example of using the Canvas class to draw something on the screen.

import javax.microedition.lcdui.*;

public class MyMIDlet extends MIDlet {


private Display display;
private MyCanvas myCanvas;

public MyMIDlet() {
display = Display.getDisplay(this);
myCanvas = new MyCanvas();
}

public void startApp() {


display.setCurrent(myCanvas); // Set the canvas as the current screen
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

// A custom Canvas class to render graphics


class MyCanvas extends Canvas {
protected void paint(Graphics g) {
// Set the background color to white
g.setColor(255, 255, 255); // RGB for white
g.fillRect(0, 0, getWidth(), getHeight());
// Set the drawing color to red
g.setColor(255, 0, 0); // RGB for red
g.fillRect(50, 50, 100, 100); // Draw a red rectangle

// Draw a string in the center


g.setColor(0, 0, 0); // RGB for black
g.drawString("Hello, Canvas!", getWidth() / 2, getHeight() / 2,
Graphics.HCENTER | Graphics.VCENTER);
}
}
}

User Interactions with the Canvas

The Canvas class provides several methods to handle user interactions, such as key presses
and pointer events (touch or stylus-based input). This is particularly important for
applications like games, where user input directly affects the graphical content.

Key Event Handling:

You can handle key events using the following methods:

 keyPressed(int keyCode): Called when a key is pressed.


 keyReleased(int keyCode): Called when a key is released.
 keyRepeated(int keyCode): Called when a key is repeatedly pressed.

Example:

public class MyCanvas extends Canvas {


protected void keyPressed(int keyCode) {
if (keyCode == KEY_NUM1) {
// Perform an action when the '1' key is pressed
}
}
}
Pointer Event Handling:

For touchscreen devices or stylus-based input, you can use the following methods:

 pointerPressed(int x, int y): Called when the user touches the screen.
 pointerReleased(int x, int y): Called when the user lifts their finger or stylus.
 pointerDragged(int x, int y): Called when the user moves their finger or stylus
while touching the screen.

Example:

java
Copy code
public class MyCanvas extends Canvas {
protected void pointerPressed(int x, int y) {
// Handle touch event (e.g., print coordinates)
System.out.println("Touched at: (" + x + ", " + y + ")");
}
}

Joystick/Arrow Key Handling:

If the device has a joystick or arrow keys, you can handle directional input using:

 upPressed(), downPressed(), leftPressed(), rightPressed(): Check if a


direction is pressed.

Graphics in the Canvas

The Graphics class in J2ME provides a set of methods to draw shapes, text, and images on
the screen. When overriding the paint(Graphics g) method in a Canvas, the Graphics
object (g) is used to perform the actual rendering.

Key Graphics Methods:

 setColor(int r, int g, int b): Sets the color for drawing using RGB values.
 fillRect(int x, int y, int width, int height): Draws a filled rectangle.
 drawRect(int x, int y, int width, int height): Draws the outline of a
rectangle.
 drawString(String str, int x, int y): Draws text on the screen.
 drawImage(Image img, int x, int y, int anchor): Draws an image at a
specified location.
 fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): Draws a filled arc (part of a circle).

Example (drawing shapes):

java
Copy code
public class MyCanvas extends Canvas {
protected void paint(Graphics g) {
// Draw a blue circle
g.setColor(0, 0, 255); // RGB for blue
g.fillArc(50, 50, 100, 100, 0, 360); // Draw a circle

// Draw a green line


g.setColor(0, 255, 0); // RGB for green
g.drawLine(10, 10, getWidth() - 10, getHeight() - 10); // Diagonal
line
}
}

Clipping Regions in the Canvas

Clipping allows you to define a specific area of the screen where drawing operations can take
place. This can improve performance, especially when drawing only part of the screen or
when animating objects within a confined area.

Setting a Clipping Region:

You can set a clipping region using the Graphics object to restrict drawing to a specific
rectangle on the screen:

 g.setClip(int x, int y, int width, int height): Defines the clipping


region.
 g.clipRect(int x, int y, int width, int height): Another way to set the
clipping area.

Once the clipping region is set, any drawing outside this area is ignored.

Example:

java
Copy code
public class MyCanvas extends Canvas {
protected void paint(Graphics g) {
// Set clipping region to a 100x100 rectangle at position (50, 50)
g.setClip(50, 50, 100, 100);

// Draw a large rectangle (only part of it will be visible)


g.setColor(255, 0, 0); // Red color
g.fillRect(0, 0, 200, 200); // Large rectangle
}
}

Animation in the Canvas

Animation in J2ME involves updating the screen at regular intervals (usually in a game loop)
to create the illusion of motion. You can implement animation using the Canvas class by
continuously repainting the screen and updating the position of objects.

Basic Animation Example:


 Create an animation loop.
 Update the position of an object on each frame.
 Call repaint() to redraw the canvas.

Example (moving a rectangle):

java
Copy code
public class MyCanvas extends Canvas {
private int x = 0;
private int speed = 2;

public MyCanvas() {
// Create a new thread to update the position of the rectangle
Thread animationThread = new Thread() {
public void run() {
while (true) {
x += speed; // Move the rectangle
4o mini

You might also like