0% found this document useful (0 votes)
155 views71 pages

Date: Experiment No. 1 Aim: To Study J2EE.: Theory

The document discusses the J2EE platform and its components. It describes the multitier architecture, containers, support for clients and business logic, and how the J2EE standard is defined and supported.

Uploaded by

mgmhacker
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
155 views71 pages

Date: Experiment No. 1 Aim: To Study J2EE.: Theory

The document discusses the J2EE platform and its components. It describes the multitier architecture, containers, support for clients and business logic, and how the J2EE standard is defined and supported.

Uploaded by

mgmhacker
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

1 Date : Experiment No. 1 Aim: To study J2EE.

Theory: J2EE Platform Overview: The J2EE platform is designed to provide server-side and client-side support for developing distributed, multitier applications. Such applications are typically configured as a client tier to provide the user interface, one or more middle-tier modules that provide client services and business logic for an application, and back-end enterprise information systems providing data management. Figure 1.1 illustrates the various components and services that make up a typical J2EE environment.

Figure 1.1 J2EE Environment

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

2 Multitier Model: As illustrated, the J2EE platform provides a multitier distributed application model. This means that the various parts of an application can run on different devices. The J2EE architecture defines a client tier, a middle tier (consisting of one or more subtiers), and a back-end tier. The client tier supports a variety of client types, both outside and inside of corporate firewalls. The middle tier supports client services through Web containers in the Web tier and supports business logic component services through Enterprise JavaBeanstm (EJBtm) containers in the EJB tier. On the back end, the enterprise information systems in the EIS tier are accessible by way of standard APIs. Container-Based Component Management: Central to the J2EE component-based development model is the notion of containers. Containers are standardized runtime environments that provide specific services to components. Components can expect these services to be available on any J2EE platform from any vendor. For example, all J2EE Web containers provide runtime support for responding to client requests, performing request-time processing (such as invoking JSP pages or servlet behavior), and returning results to the client. In addition, they provide APIs to support user session management. All EJB containers provide automated support for transaction and life cycle management of EJB components, as well as bean lookup and other services. Containers also provide standardized access to enterprise information systems; for example, providing access to relational data through the JDBC API. In addition, containers provide a mechanism for selecting application behaviors at assembly or deployment time. Through the use of deployment descriptors (XML files that specify component and container behavior), components can be configured to a specific container's environment when deployed, rather than in component code. Features that can be configured at deployment time include security checks, transaction control, and other management responsibilities. While the J2EE specification defines the component containers that a platform implementation must support, it doesn't specify or restrict the containers' configurations. Thus, both container types can run on a single platform, Web containers can live on one platform and EJB containers on another, or a J2EE platform can be made up of multiple containers on multiple platforms.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

3 Support for Client Components : The J2EE client tier provides support for a variety of client types, both within the enterprise firewall and outside. Clients can be offered through Web browsers by using plain HTML pages, HTML generated dynamically by JavaServer Pagestm (JSPtm) technology, or Java applets. Clients can also be offered as stand-alone Java language applications. J2EE clients are assumed to access the middle tier primarily using Web standards, namely HTTP, HTML, and XML. Because of its flexible programming model, the J2EE platform can support a number of simple application models implemented primarily on the strengths of its Web tier component technologies. To support more complex user interactions, it may be necessary to provide functionality directly in the client tier. This functionality is typically implemented as JavaBeanstm components that interact with the service in the middle tier via servlets. Client-tier JavaBeans components would typically be provided by the service as an applet that is downloaded automatically into a user's browser. To eliminate problems caused by old or non-standard versions of the Java Virtual Machine in a user's browser, the J2EE application model provides special support for automatically downloading and installing the Java Plug-in. In addition, the J2EE platform is flexible enough to support alternate client models easily, including wireless phones and handheld devices that use programming models provided by the Java 2 Platform, Micro Edition. Client-tier beans can also be contained in a stand-alone application client written in the Java programming language. In this case, the enterprise typically would make the client available for users to download from a browser using Java Web Start technology. Java Web Start technology makes application deployment portable by providing browser-based download and installation mechanisms. With both application and deployment portability, this ensures that users can always access and work with the latest versions of stand-alone application clients. If desired, non-Java clients such as Visual Basic programs can present J2EE services to users. Since the service is presented by servlets in the middle tier to first-tier clients using the standard HTTP protocol, it is easy to access it from practically any program running on any operating system.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

4 Support for Business Logic Components : While simple J2EE applications may be built largely in the client tier, business logic is often implemented on the J2EE platform in the middle tier as Enterprise JavaBeans components (also known as enterprise beans). Enterprise beans allow the component or application developer to concentrate on the business logic while the complexities of delivering a reliable, scalable service are handled by the EJB container. In many ways, the J2EE platform and EJB architecture have complementary goals. The EJB component model is the backbone of industrial-strength application architectures in the J2EE programming model. The J2EE platform complements the EJB specification by:

Fully specifying the APIs that an enterprise bean developer can use to implement enterprise beans

Defining the larger, distributed programming environment in which enterprise beans are used as business logic components

Support for the J2EE Standard : The J2EE standard is defined through a set of related specifications. Key among these are the J2EE specification, the Enterprise JavaBeans specification, the Java Servlet specification, and the JavaServer Pages specification. Together, these specifications define the architecture described in this book. In addition to the specifications, several other technology deliverables support the J2EE standard, including the J2EE Compatibility Test Suite, the J2EE reference implementation, and the J2EE SDK. The J2EE Compatibility Test Suite (CTS) helps maximize the portability of applications by validating the specification compliance of a J2EE platform product. This test suite begins where the basic Java Conformance Kit (JCK) leaves off. The CTS tests conformance to the Java standard extension APIs that are not covered by a JCK. In addition, it tests a J2EE platform's ability to run standard end-to-end applications.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

5 The J2EE reference implementation, a complete implementation of the J2EE standard provided by Sun Microsystems, represents an operational definition of the J2EE platform. It is used by licensees as the "gold standard" to determine what their product must do under a particular set of application circumstances. It is the standard platform for running the J2EE Compatibility Test Suite, and it can be used by developers to verify the portability of an application. The J2EE reference implementation is available in both binary and source code form. The J2EE SDK, based on the J2EE reference implementation binary, is provided freely to the developer community to help expedite developer adoption of the J2EE standard. Although not a commercial product and not available for commercial use, the J2EE SDK is useful for developing application demos and prototypes, such as the Java Pet Store sample application described in this book. The J2EE SDK also includes application verification and deployment tools to simplify development, and the J2EE Tutorial, which provides step-by-step examples and information that developers need to begin working with the platform. Another word on J2EE standards and portability: The J2EE specifications have, by design, set the platform-compatibility bar at a level that's relatively easy to clear. Because the platform specifications are developed collaboratively, platform vendors must have plenty of opportunity to supply J2EE platform implementations. Obvious and unreasonable implementation hurdles were avoided. For example, there are no restrictions on vendors adding value to J2EE products by supporting services not defined in the specifications. While the J2EE standard is designed to encourage component portability, specific results are primarily a function of how a component uses services provided by its container. Vendorspecific features limit component portability. The J2EE specifications spell out a base set of capabilities that a component can count on, providing components with a level of cross-container portability. Needless to say, an application developer expecting to deploy on a specific vendor implementation of the J2EE platform should be able to do so across a wide range of operating systems and hardware architectures.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

Quiz :

1. What is EJB containers?

2. What is JDBC API?

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

8 Date: Experiment No.: 2 Name of the Experiment: Creation of Simple J2ME MIDlet. Aim: Write a J2ME program to display Welcome to MGMCET. Software requirement: Java Platform, Standard Edition version 1.4.2 or higher, Sun Java Wireless Toolkit 2.5.2_01 for CLDC, Text editor. Prerequisite: Java programming. Theory: MIDletA MIDlet is an application that uses the Mobile Information Device Profile (MIDP) of the Connected Limited Device Configuration (CLDC) for the Java ME environment. Typical applications include games running on mobile devices and cell phones which have small graphical displays, simple numeric keypad interfaces and limited network access over HTTP. MIDlet Life cycleA MIDlet lifecycle have following steps... startApp() pauseApp() destroyApp() By default MIDlet is in the paused states. when the application is executed by default startApp() method will call and when close the application the destroyApp() method will be called. But when your constructor is not null type then it will be executed firstly. Display class:MIDP contains user interface classes in the javax.microedition.lcdui and

javax.microedition.lcdui.game packages. The devices display, as seen by the MIDlet, is represented by an instance of the Display class, accessed from a factory method, getDisplay(). Displays main purpose in life is to keep track of what is currently shown, which is an instance T.E. SEM VI (IT): Programming for Mobile and Remote Computers
Prepared By: Diksha Kale

9 of Displayable. Only one Displayable object can be displayed at any given time.Displayable has a small family of subclasses that represent various types of user interfaces. display = Display.getDisplay(this); display.setCurrent(form); The first of the two lines just shown obtains a reference to a Display object. The Display object is a Java object that represents the physical display of the device's screen. The next line says,"Make this form the currently displayed entity." Sample Program: //include the MIDlet super class //include the GUI libraries of MIDP import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class Demo extends MIDlet{ private Form form; //Initialize the Midlet Display variable private Display display; // Define the no-argument constructor. public Demo(){ super(); }public void startApp(){ form = new Form("Display"); String msg = "Welcome to MGMCOE"; form.append(msg); // Retrive the display from the static display object. display = Display.getDisplay(this); display.setCurrent(form); }public void pauseApp(){} public void destroyApp(boolean unconditional){ notifyDestroyed(); }}

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

10

Steps to execute the MIDlet: 1. Install following software a. Java Platform, Standard Edition version 1.4.2 or higher. (version 1.5.0 is now available to download) b. Sun Java Wireless Toolkit for CLDC This is a package of tools for building and testing MIDlets. c. Text editor. This can be something as rudimentary as Notepad (on Windows) or something more elaborate like jEdit. 2. To run the toolkit itself, select the Wireless Toolkit 2.5.2 shortcut. You should see the following screen.

3. Click on New Project in the button bar. The toolkit prompts you for a project name and the name of a MIDlet class in the project.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

11

4. Press Create Project to finish creating the new project. In the text output pane of the Sun Java Wireless Toolkit, you'll see several helpful messages telling you where to store the project's source files. Creating project "MIDletDemo" Place Java source files in "C:\j2mewtk\2.5.2\apps\MIDletDemo\src" Place Application resource files inC:\j2mewtk\2.5.2\apps\MIDletDemo\res" Place Application library files inC:\j2mewtk\2.5.2\apps\MIDletDemo\lib" 5. Save the code as Demo.java in the src directory of your project. On my computer, this file is saved in C:\j2mewtk\2.5.2\apps\MIDletDemo\src\Demo.java 6. Next, press the Build button in Wireless Toolkit 2.5.2. The toolkit will attempt to compile your project. If there are any compiler errors, you'll see them in the text output area of Wireless Toolkit 2.5.2. Fix the errors until the project builds successfully. 7. Now you're ready to test your MIDlet suite. Click on the Run button. You should see a mobile phone emulator pop up: Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

12

Lab Exercise: 1. Create a MIDlet to display your Name, Address, and Phone Number. 2. Create a MIDlet to pick a number randomly and display it on screen. 3. Create a MIDlet to display todays date and current time on screen.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

13

Date: Experiment No: 3 Aim: To study J2ME MIDlets.

Software requirement: Java Platform, Standard Edition version 1.4.2 or higher, Sun Java Wireless Toolkit 2.5.2_01 for CLDC, Text editor. Prerequisite: Java programming. Theory :

J2ME: Java Platform, Micro Edition, or Java ME, is a Java platform designed for embedded systems. Target devices range from industrial controls to mobile phones and set-top boxes. Java ME was formerly known as Java 2 Platform, Micro Edition (J2ME). MIDlet: MIDlet application is an applet that runs in small devices. Like an applet the midlet has a life cycle. The core package which addresses the midlet life cycle is javax.microedition.midlet. Each state of life cycle is notified to Application Management Software(AMS) and the AMS acts appropriately. AMS is the device software that handles the midlet lifecycle. AMS interacts with the MIDlet application in loading and unloading the MIDlet using the MIDlet's life cycle methods and thus affecting the following midlet states.

Paused State Active State

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

14

Destroyed State

MIDlet class is an Abstract class and your application's root class must extend this class and override its abstract methods. The MIDlet Lifecycle: Mobile devices, whether emulators or real, interact with a MIDlet using their own software, which is called Application Management Software (AMS). The AMS is responsible for initializing, starting, pausing, resuming, and destroying a MIDlet. (Besides these services, AMS may be responsible for installing and removing a MIDlet, as well.) To facilitate this management, a MIDlet can be in one of three states which is controlled via the MIDlet class methods, that every MIDlet extends and overrides. These states are active, paused and destroyed.

Figure 11. The possible states of a MIDlet and the transition between them As you can see from Figure 11, an installed MIDlet is put into a paused state by the AMS creating an instance of it, by calling its no-args constructor. This is of course, not the only way that the MIDlet can be in a paused state. It can enter this state when the AMS calls the pauseApp() method on an active MIDlet (and the method returns successfully). It can also enter this state when the MIDlet pauses itself by calling the notifyPaused() method, as opposed to the

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

15 pauseApp() method, which is called by the AMS. However, what exactly is happening with the MIDlet in the paused state? In a paused state, the MIDlet is waiting for a chance to get into the active state. Theoretically, in this state, it should not be holding or using any of the device resources and should be passive in nature. Once the MIDlet is created, this is the state to be in before becoming active. Also, entering the paused state is necessary when the device requires it to consume fewer resources, because these resources may be required for handling other device functions, like handling an incoming call. This is when the device invokes the pauseApp() method through the AMS. If the MIDlet should inform the AMS that it has paused, it should invoke the notifyPaused() method, which tells the AMS that the MIDlet has indeed paused. One final way in which a MIDlet can get into a paused state is when the MIDlet's startApp() method, which is called when the AMS invokes it to start the MIDlet (either the first time or from a paused state), throws a MIDletStateChangeException. Essentially, in case of an error, the MIDlet takes the safe road of staying in the paused state. The active state is where every MIDlet wants to be! This is when the MIDlet can do its functions, hold the device resources and generally, do what it is supposed to do. As said previously, a MIDlet is in an active state when the AMS calls the startApp() method on a paused MIDlet (actually, the MIDlet enters the active state just before this method is called by the AMS). A paused MIDlet can request to go into the active state by calling the method resumeRequest(), which informs the AMS that the MIDlet wishes to become active. The AMS may of course, choose to ignore this request or, alternatively, queue it if there are other MIDlets requesting the same. The destroyed state is entered when a MIDlet's destroyApp(boolean unconditional) method is called and returns successfully, either from an active or paused state. This method is called by the AMS when it feels that there is no need for the MIDlet to keep running and is the place the MIDlet may perform cleanup and other last minute activities. The MIDlet can enter this state itself, by calling the notifyDestroyed() method, which informs the AMS that the MIDlet has cleaned up its resources and is eligible for destruction. Of course, since in this case, the T.E. SEM VI (IT): Programming for Mobile and Remote Computers
Prepared By: Diksha Kale

16 destroyApp(boolean unconditional) method is not called by the AMS, any last-minute activities must be done before this method is invoked. What happens if the AMS calls the destroyApp(boolean unconditional) method in the middle of an important step that the MIDlet may be doing, and may be loath to be destroyed? This is where the Boolean unconditional flag comes into the picture. If this flag is set to true, the MIDlet will be destroyed, irrespective of what the MIDlet is doing. However, if this flag is false, effectively, the AMS is telling the MIDlet that it wants the MIDlet to be destroyed, but if the MIDlet is doing something important, it can raise a MIDletStateChangeException, and the AMS will not destroy it just yet. However, note that even then, there are no guarantees that the MIDlet will not be destroyed, and it remains up to each device to decide how they should handle the request. If the device does honor the MIDlet's request, it may try and invoke the destroyApp(boolean unconditional) at a later stage. Note that a destroyed state means that the MIDlet instance has been destroyed, but not uninstalled from the device. The MIDlet remains installed in the device, and a new instance of it may be created later. Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

17 Program: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class FirstMidlet extends MIDlet { private Display display; TextBox box = null; public FirstMidlet() { } public void startApp() { display = Display.getDisplay(this); box = new TextBox("FirstExample","Welcome to Mobile Programming",100,0); display.setCurrent(box); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

18 Quiz: 1. What is J2ME?

2. What is the role of destroyApp?

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

19

Date: Experiment No: 4 Aim : To Study Low level API using Canvas. Software requirement: Java Platform, Standard Edition version 1.4.2 or higher, Sun Java Wireless Toolkit 2.5.2_01 for CLDC, Text editor. Prerequisite: Java programming. Theory :

Low-Level API The low-level API provides little abstraction. It is designed for applications that need precise placement and control of graphic elements and access to low-level input events. This API gives the application full control over what is being drawn on the display. The Canvas and Graphics classes implement the low-level API. It is important to note that MIDlets that access the low-level API are not guaranteed to be portable because this API provides mechanisms to access details that are specific to a particular device. MIDP also gives you a low level component called Canvas for pixel level access. Low level components can be used to create basic drawings and create custom components. This lesson takes you through the nitty-gritty's of using these Low Level API's Canvas class should be extended for low level access. This class provides paint() method which has to be implemented for drawing on to the Canvas. public void paint(Graphics graphics) { graphics.drawString("Salsa Drawings", 0, 0, Graphics.TOP|Graphics.LEFT); } Method paint() takes a Graphics instance as parameter. With Graphics we can draw items like arc, rectangle, line, image, triangle, circle etc. Different parameters like fonts, colors, anchors can also be specified. T.E. SEM VI (IT): Programming for Mobile and Remote Computers
Prepared By: Diksha Kale

20 Determine Screen Size To determine the screen size call methods getWidth() and getHeight().

Figure 1. Low-level MIDP 2.0 UI classes Color Color can be manipulated using Method setGrayScale() which gives you black and white colors and setColor() to set RGB Colours. When setColor() is called all subsequent operations are rendered in this color unless setColor() is called with another color. This method takes three parameters representing Red, Blue and Green hues to construct a color. Each of these parameters can have a value between 0 and 225. Following examples give you the usage. Graphics.setColor(255,255,255) for White. Graphics.setColor(0,0,0) for black. Graphics.setColor(50,50,50) Graphics.setColor(100,100,100) Graphics.setColor(60,10,105) Following code listing gives you the idea to user colors. public void paint(Graphics graphics) { graphics.setColor(255,255,255); // Set color to white graphics.fillRect(0, 0, getWidth(), getHeight()); graphics.setColor(0,0,0); // Reset color to black graphics.drawString("This is a very boring MIDlet "+ "and I wanna sleep!", 0, 0, Graphics.TOP|Graphics.LEFT); }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

21

Figure: The MIDP Classes

Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

22

Program: Low level API using Canvas Draw Rectangle import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class DrawRectangle extends MIDlet { private Display display; private MyCanvas canvas; public DrawRectangle() { display = Display.getDisplay(this); canvas = new MyCanvas(this); } protected void startApp() { display.setCurrent(canvas); } protected void pauseApp() { } protected void destroyApp(boolean unconditional) { } } class MyCanvas extends Canvas { private DrawRectangle rectangleExample; public MyCanvas(DrawRectangle rectangleExample) { this.rectangleExample = rectangleExample; } protected void paint(Graphics g) { g.setColor(255, 255, 255); g.setColor(255, 0, 0); g.fillRect(2, 2, 20, 20); g.drawRect(2, 2, 20, 20); g.setColor(0, 255, 0); g.drawRoundRect(20, 20, 60, 60, 15, 45); }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

23

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

24 Quiz:

1.Which of the following statements is true? A Canvas Can be rendered on to a Form B Form Can be rendered on to a Canvas C Canvas and Form cannot be mixed D Canvas and Form can be rendered on to an Image 2. When a string is drawn to a Canvas and the String size is more than the screen width. A The text wraps B The text does not wrap and some of the text is not visible. C The text collapses D None of the above 3. Canvas co-ordinate system has the co-ordinate (0,0) at which position? A Top Left corner B Bottom Left corner C Middle of the screen D None of the above 4. Vertical and horizontal alignment of images is done by ____________ A Items B Screens C Sprites D Anchors

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

25

5. Which method of Canvas class should be implemented to draw an image on a Canvas? A keyPressed() B draw() C paint() D none of the above

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

26 Date: Experiment No. : 5 Aim : To implement J2ME MIDlet using Ticker class. Software requirement: Java Platform, Standard Edition version 1.4.2 or higher, Sun Java Wireless Toolkit 2.5.2_01 for CLDC, Text editor. Prerequisite: Java programming.

Theory: The Ticker component presents a horizontal scrolling banner. The only parameter you can specify for the Ticker is the text message to display. The rate and direction of the scrolling is determined by the device implementation.

The constructor for Ticker is as follows: Ticker(String str) Ticker component is not a subclass of Screen. Rather, Ticker is a variable in the Screen class. This means that a Ticker can be attached to any subclass of Screen, including an Alert. Figure. The complete device display hierarchy

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

27

Finally, here is the definition of Ticker, as shown inside the Screen class: public abstract class Screen extends Displayable { ... private Ticker ticker = null; ... }

The final MIDlet we will create together for this first half of the tutorial utilizes a List component and a Ticker component. The Ticker scrolls across the top of the display, while the List shows a series of products. Here are the steps to create the TickerTest MIDlet: 1. Create a new project with the name TickerTest. 2. Copy and paste the TickerTest source code into a text editor. 3. Save the source code as TickerTest.java in the directory \apps\TickerTest\src of your WTK installation. 4. Build and run the project. And it has two methods:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

28 getString():- This is the String type methods which Gets the string currently being scrolled by the ticker. setString(String str):- This is the void type, it Sets the string to be displayed by this ticker.

Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

29 Program: Ticker example: import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class TickerExample extends MIDlet implements CommandListener{ private Display display; private Ticker ticker; private Command exit; private Form form; public TickerExample(){ form = new Form("BSE Stock Exchange Ticker"); display = Display.getDisplay(this); ticker = new Ticker ("10/17/2008 3:59:59 PM ACC LTD 489.05 (-6.42%) BHARTI ARTL 676.80 (-7.47%) BHEL 1,194.80 (-9.00%) ACC LTD 489.05 (-6.42%) BHARTI ARTL 676.80 (-7.47%) BHEL 1,194.80 (-9.00%) DLF LTD* 291.30 (-10.34%) GRASIM INDUSTRIES LTD. 1,293.40 (-5.71%) HDFC BANK LT 1,024.05 (-5.82%)"); exit = new Command("Exit", Command.SCREEN, 1); form.addCommand(exit); form.setCommandListener(this); form.setTicker(ticker); } public void startApp(){ display.setCurrent(form); } public void pauseApp(){ } public void destroyApp(boolean unconditional){ notifyDestroyed(); } public void commandAction(Command c, Displayable display){ String label = c.getLabel(); if (label.equals("Exit")){

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

30 destroyApp(false); } } }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

31

Quiz : 1. What are methods of ticker?

2. What is Displayable class?

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

32 Date: Experiment No. : 6 Aim: To study Interactive gauge application. Software requirement: Java Platform, Standard Edition version 1.4.2 or higher, Sun Java Wireless Toolkit 2.5.2_01 for CLDC, Text editor. Prerequisite: Java programming.

Theory: The Gauge component A Gauge component displays a progress-meter style interface. There are two types of Gauge: interactive and non-interactive. The former allows the user to make changes to the gauge. The latter requires the developer to update the gauge.

Here's the constructor for the Gauge component:

Gauge(String label, boolean interactive, int maxValue, int initialValue)

And here's a short code block that creates an interactive Gauge:

private Gauge gaVolume; // Volume adjustment gaVolume = new Gauge("Sound Level", true, 100, 4);

The InteractiveGauge MIDlet Follow these steps to create a MIDlet with an interactive gauge: 1. Create a new project with the name InteractiveGauge. 2. Copy and paste the InteractiveGauge source code into a text editor.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

33 3. Save the source code as InteractiveGauge.java in the directory \apps\InteractiveGauge\src of your WTK installation. 4. Build and run the project.

The complete device display hierarchy

Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

34

Program: /*-------------------------------------------------* InteractiveGauge.java *-------------------------------------------------*/ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class InteractiveGauge extends MIDlet implements CommandListener { private Display display; // Reference to display object private Form fmMain; // The main form private Command cmExit; // Exit the form private Gauge gaVolume; // Volume adjustment public InteractiveGauge() { display = Display.getDisplay(this); // Create the gauge and exit command gaVolume = new Gauge("Sound Level", true, 50, 4); cmExit = new Command("Exit", Command.EXIT, 1); // Create form, add commands, listen for events fmMain = new Form(""); fmMain.addCommand(cmExit); fmMain.append(gaVolume); fmMain.setCommandListener(this); } // Called by application manager to start the MIDlet. public void startApp() { display.setCurrent(fmMain); }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

35 public void pauseApp() {} public void destroyApp(boolean unconditional) {} public void commandAction(Command c, Displayable s) { if (c == cmExit) { destroyApp(false); notifyDestroyed(); } } } output: interactive gauge

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

36

Quiz : 1. How to Create the gauge and exit command?

2. Which constructor is use for the Gauge component?

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

37 Date: Experiment No: 7 Aim: To study High level API components. Software requirement: Java Platform, Standard Edition version 1.4.2 or higher, Sun Java Wireless Toolkit 2.5.2_01 for CLDC, Text editor. Prerequisite: Java programming. Theory:

High-level API : Any class those subclasses a Screen is a High Level User Interface. High-Level API gives us a rich set of readymade UI components for user interaction like alerts, forms, lists etc. The high-level API is designed for applications whose client parts run on mobile information devices where portability is important. To achieve portability, the API employs a high-level abstraction and gives you little control over its look and feel. For example, you cannot define the visual appearance (shape, color, or font) of components. Interaction with components is encapsulated by the implementation and the application is not aware of such interactions. When you use the high-level API, the underlying implementation does the necessary adaptation to the device's hardware and native user interface style. The high-level API is implemented by classes that inherit from the Screen class. Classes and its Description:

Classes

Description

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

38 Alert AlertType Canvas ChoiceGroup Command DateField Display Displayable Font Form Gauge Graphics Image ImageItem Item List Screen StringItem TextBox TextField Ticker A screen that shows data to the user and waits for a certain period of time before proceeding to the next screen. Indicates the nature of the alerts. The base class for writing applications that need to handle low-level events and to issue graphics calls for drawing to the display. A group of selectable elements intended to be placed within aForm. A construct that encapsulates the semantic information of an action. An editable component for presenting calendar date and time information that may be placed into aForm. Represents the manager of the display and input devices of the system. An object that has the capability of being placed on the display. Represents fonts and font metrics. A screen that contains an arbitrary mixture of items (images, text, text fields, choice groups, for instance.) Implements a bar graph display of a value intended for use in a form. Provides simple 2D geometric rendering capability. Holds graphical image data. Provides layout control whenImageobjects are added to aFormorAlert. A superclass for components that can be added to aFormorAlert. A screen containing a list of choices. The superclass of all high-level user interface classes. An item that can contain a string. A screen that allows the user to enter and edit text. An editable text component that can be placed into aForm. A ticker-type piece of text that runs continuously across the display. It can be attached to all screen types exceptCanvas.

Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

39 Program: Use of High level Components AlertDemo import java.util.Date; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.Display; import javax.microedition.midlet.MIDlet;

public class AlertDemo extends MIDlet {

Alert alert;

public AlertDemo() { alert = new Alert("Alert!"); alert.setString("Message has been delivered on " + new Date().toString()); alert.setTimeout(10000); }

public void startApp() { Display.getDisplay(this).setCurrent(alert); }

public void pauseApp() { }

public void destroyApp(boolean unconditional) { } }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

40

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

41

Quiz : 1. What is Display and Displayable class?

2.List High level API classes?

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

42

Date: Experiment No. : 8 Aim: To study of RMS. Software requirement: Java Platform, Standard Edition version 1.4.2 or higher, Sun Java Wireless Toolkit 2.5.2_01 for CLDC, Text editor. Prerequisite: Java programming. Theory: The RMS API abstracts the device-dependent details of the storage area and access to those details, and it provides a uniform mechanism to create, destroy, and modify data. This ensures portability of MIDlets to different devices. RMS Data Storage Model The RMS supports the creation and management of multiple record stores, shown in Figure below. Arecord store is a database whose central abstraction is the record. Each record store consists of zero or more records. A record store name is case sensitive and can consist of a maximum of 32 Unicode characters. A record store is created by a MIDlet.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

43

MIDlets within the same MIDlet suite can share one another's record stores. A MIDlet suite defines a name space for record stores; a record store must have a unique name within a MIDlet suite. The same name can be used in different MIDlet suites, however. MIDlets can list the names of all the record stores available to them. They can also determine the amount of free space available for storing data. Incidentally, you should be aware that when all MIDlets in a MIDlet suite are removed from a device, the device AMS removes all record stores in the MIDlet suite namespace. All persistent data will be lost. For this reason, you should consider designing applications to include a warning or confirmation that requires users to acknowledge that they understand the potential loss of data when they remove applications. Applications might also include a mechanism to back up the records in a data store to another location. This might require server side support.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

44 The RMS defines the following conceptual operations on an individual record store: Add a record. Delete a record. Change a record. Look up (retrieve) a record. Enumerate all records. Records are uniquely identified by a record ID, which is the only primary key type supported. The type of all record ids is the Java built-in type int. The RMS has no support for featuressuch as tables, rows, columns, data types, and so forththat are present in relationaldatabases.

Records A record is a byte array of type byte []. The RMS doesn't support the definition or formatting of fields within a record. Your application must define the data elements within a record and their format. The reader of a record, therefore, must be aware of the format that was used to write the record. Because a record is simply a byte array, applications must convert data from arbitrary types to bytes when writing records, and they must convert from bytes to those types upon reading the data. Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

45

Program: RMSMidlet import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import javax.microedition.rms.*;

public class RMSMidlet extends MIDlet implements CommandListener { private Command exitCommand; private Display display; public RMSMidlet() { display = Display.getDisplay(this); exitCommand = new Command("Exit",Command.SCREEN,1); } public void startApp() { TextBox t = new TextBox("Name and Email",null,295,TextField.ANY); RecordStore rs = null; byte[] nameEmail1 = null; byte[] nameEmail2 = null; try { rs = RecordStore.openRecordStore("RMS",true); }

catch(RecordStoreException ex) { try { nameEmail1 = "[email protected]".getBytes(); nameEmail2 = "[email protected]".getBytes(); rs.addRecord(nameEmail1,0,nameEmail1.length); rs.addRecord(nameEmail2,0,nameEmail2.length); rs.closeRecordStore(); } T.E. SEM VI (IT): Programming for Mobile and Remote Computers
Prepared By: Diksha Kale

ex.printStackTrace();

46 catch(Exception e) { }

String result1 = new String(nameEmail1); int position1 = result1.indexOf('@'); result1 = "Name:" + result1.substring(0,position1) + "\n" + "E-mail:" +result1.substring(0,result1.length()); String result2 = new String(nameEmail2); int position2 = result2.indexOf('@'); result2 = "Name:" + result2.substring(0,position2) + "\n" + "E-mail:" +result2.substring(0,result2.length()); String result = result1 +result2; t.setString(result); t.addCommand(exitCommand); t.setCommandListener(this); display.setCurrent(t); } public void pauseApp() { }

public void destroyApp(boolean unconditional) { }

public void commandAction(Command c, Displayable d) { destroyApp(false); notifyDestroyed(); }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

47

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

48

Quiz : 1. What is the acronym for RMS? A Resource Management System B Record Management System C Research Management System D Risk Management System

2.What is the relation between RMS and Oracle Lite? A No relation, both are separate mobile databases B RMS sits on Oracle C RMS and Oracle sit on SQL Server CE

3. What is analogous to database trigger? A RecordListener B RecordFilter C Dictionary D Enumeration

4. How many columns can be there for each Record in a RMS system excluding the default Record ID column? A 4 B 1 C 3 D 10

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

49 5. Record in RMS can have following constraint defined A Primary Key B Foreign Key C Not Null D Constraints cannot be defined in RMS

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

50

Date: Experiment No. : 9 Aim: To Creating custom items and performing various operations. Software requirement: Java Platform, Standard Edition version 1.4.2 or higher, Sun Java Wireless Toolkit 2.5.2_01 for CLDC, Text editor. Prerequisite: Java programming. Theory: In J2ME applications, Custom Items can be created by programmers and they can also set their look and feel as these custom item have their own method called paint(). Also CustomItem is a extendable class, and extends the Item class itself. Using custom items you can create and add as many items as you want in your J2ME applications. In this Midlet, we have tried to do the same thing. Form-based custom components are available to MIDP 2.0 applications, however, through the CustomItem class, a new addition to the javax.microedition.lcdui package. Like all form items, CustomItem extends the Item class. Applications can't extend Item directly because it defines no public or protected constructors, but CustomItem is designed to be extended. In particular, it defines the event methods that custom components require, to draw themselves, and to process user input. Defining a custom item is a matter of subclassing CustomItem and implementing five abstract methods: This custom item fills its content area - the area for which it is solely responsible for drawing and processing input - with the color white, and does not respond to any input events. Not a very

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

51 useful item, to be sure, but a complete implementation nonetheless, and enough to understand the basic features of a custom item. First, like any other item, a custom item has an optional label, a string that identifies the item on the device's display. To ensure consistency, the drawing and positioning of the label is done by the system, not the application, outside the content area. You can omit the label by setting it to null. The actual dimensions of the item include space for the label as well as for any borders or other visual effects provided by the system - the content area is a subset of the item's total area. Second, items in MIDP 2.0 have the concept of minimum and preferred content area dimensions. These are familiar concepts if you've ever written a component for the J2SE Abstract Windowing Toolkit (AWT). When performing layout calculations, the system can ask an item for the preferred dimensions of its content area - the optimal height and width for the item - by invoking getPrefContentHeight() and getPrefContentWidth(). To obtain the minimum

dimensions of the content area, which should be less than or equal to the preferred dimensions, the system invokes getMinContentHeight() and getMinContentWidth(). Note that when the system queries an item for its preferred dimensions, it may already have calculated some preliminary layout information. Thus, when the system invokes getPrefContentHeight(), it passes a tentative value for the content area width (not the height). Similarly, it

passes getPrefContentWidth() a tentative value for the content area height. The methods use these tentative values for the opposite dimension to compute the preferred values for the queried dimension. If no tentative value is available, the system passes -1 to the methods. Third, custom items draw themselves by implementing a paint() method, very much the way canvases do. The custom item's paint() method, however, is passed height and width parameters along with the necessary Graphics object. These additional parameters are the current dimensions of the item's content area. All drawing is clipped to these dimensions. The drawing origin is the top left corner of the content area. Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

52

Program: Custom item import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class CustomItemMIDletExample extends MIDletimplements CommandListener{ private Form form; private Command exit; private Display display; private CustomItemExample customItem; public CustomItemMIDletExample(){ form = new Form("CustomItemMIDletExample"); exit = new Command("Exit", Command.EXIT, 0); form.append(new CustomItemExample("CustomItemExample")); form.addCommand(exit); form.setCommandListener(this); } public void startApp(){ display = Display.getDisplay(this); display.setCurrent(form); } public void pauseApp(){} public void destroyApp(boolean unconditional){} public void commandAction(Command c, Displayable s){ if(c.getCommandType() == Command.EXIT) notifyDestroyed(); } } class CustomItemExample extends CustomItem{ public CustomItemExample(String title){ T.E. SEM VI (IT): Programming for Mobile and Remote Computers
Prepared By: Diksha Kale

53 super(title); } public int getMinContentWidth(){ return 100; } public int getMinContentHeight(){ return 60; } public int getPrefContentWidth(int width){ return getMinContentWidth(); } public int getPrefContentHeight(int height){ return getMinContentHeight(); } public void paint(Graphics g, int w, int h){ g.drawRect(0, 0, w - 1, h - 1); g.setColor(0, 0, 255); int offset = 0; for (int y = 4; y < h; y += 12){ offset = (offset + 12) % 24; for (int x = 7; x < w; x += 24){ g.fillTriangle(x + offset, y, x + offset - 3, y + 6, x + offset + 3, y + 6); } } } }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

54 Output:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

55 Quiz:
1.

Define classes of custom items.

2.Comment on getPrefContentHeight()

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

56 Date: Experiment No. 10 Aim: Write a J2ME program to insert an image in a Canvas. Theory: There are two types of images that can be displayed. 1) Immutable 2) Mutable -An immutable images are loaded from a file or other resources and cannot be modified once the image is displayed. Examples. Icon s associated with MIDlets are immutable. -A mutable image is drawn on the Canvas using methods available in Graphics class. -An immutable image can be drawn on the screen as well as on Canvas. whereas mutable image is drawn only on the canvas.

The Canvas Class: Each MIDlet has a one instance of the Display class, and the Display class has a one derived class called 'displayable'. Everything a MIDlet displays on the Screen is created by an instance of a Displayable class.

The Display class hierarchy is shown below: public class Displayable public abstract class Displayable public abstract class Screen extends Displayable public abstract class Canvas extends Displayable public class Graphics The screen class is used to create high-level components. the Canvas class is used to gain lowlevel access to display.

Creating an Image using Image class: Create an instance of an Image class by calling the createImage() method of the Image class.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

57 private Image img; img = Image.createImage(path); Displaying an Image on a Canvas Once the image is created , it can be drawn on the Canvvs using drawImage() method of the Graphics class. Graphics.drawImage() drawImage() method takes four parameters.
_ First

parameter is the reference to the image that you want to display. and third parameters indicate position of the image on Canvas. parameter specifies the portion of the image bounding box that is placed at the specified

_ second _ Fourth

co-ordinate position. Example: This example is will show you how to create the image at the top center of the screen. The following are the methods used in this class:

getAltText() getImage() getLayout() setAltText(String text) setImage(Image img) setLayout(int layout)

Following fields have been used in this class: LAYOUT_CENTER:- Image should be horizontally centered. LAYOUT_DEFAULT:- Use the default formatting of the "container" of the image. LAYOUT_LEFT:- Image should be close to left-edge of the drawing area. LAYOUT_NEWLINE_AFTER:- A new line should be started after the image is drawn. LAYOUT_NEWLINE_BEFORE:- A new line should be started before the image is drawn. LAYOUT_RIGHT:- Image should be close to right-edge of the drawing area.

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

58

Conclusion : Displaying an image on a Canvas has been studied Program:

import java.io.IOException; import javax.microedition.midlet.*; import javax.microedition.lcdui.*;

public class ImageItemExample extends MIDlet implements CommandListener{ private Display display; private Command exit; private Form form; private ImageItem logo;

public ImageItemExample(){ form = new Form("Image Item"); exit = new Command("Exit", Command.EXIT, 0); try{ logo = new ImageItem(null, Image.createImage("/logo.png"), ImageItem.LAYOUT_CENTER | ImageItem.LAYOUT_NEWLINE_BEFORE | ImageItem.LAYOUT_NEWLINE_AFTER, "Roseindia"); form.append(logo); }catch(IOException e){ form.append(new StringItem(null, "Roseindia: Image not available: "+ e)); } }

public void startApp(){ display = Display.getDisplay(this); form.addCommand(exit); form.setCommandListener(this); display.setCurrent(form); }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

59

public void pauseApp(){}

public void destroyApp(boolean unconditional){ notifyDestroyed(); }

public void commandAction(Command c, Displayable d){ String label = c.getLabel(); if(label.equals("Exit")){ destroyApp(true); } } }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

60

Output:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

61 Quiz : 1.Which of the following statements is true? A Canvas Can be rendered on to a Form B Form Can be rendered on to a Canvas C Canvas and Form cannot be mixed D Canvas and Form can be rendered on to an Image 2. When a string is drawn to a Canvas and the String size is more than the screen width. A The text wraps B The text does not wrap and some of the text is not visible. C The text collapses D None of the above 3. Canvas co-ordinate system has the co-ordinate (0,0) at which position? A Top Left corner B Bottom Left corner C Middle of the screen. D None of the above 4. Vertical and horizontal alignment of images is done by ____________ A Items B Screens C Sprites D Anchors

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

62 5. Which method of Canvas class should be implemented to draw an image on a Canvas? A keyPressed() B draw() C paint() D none of the above

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

63 Date: Experiment No: 11 Aim : To study Mixing 3D Graphics Software requirement: Java Platform, Standard Edition version 1.4.2 or higher, Sun Java Wireless Toolkit 2.5.2_01 for CLDC, Text editor. Prerequisite: Java programming.
Theory:

The API The Mobile 3D Graphics API for J2ME is defined in the package javax.microedition.m3g, which provides an easy-to-use API for rendering 3D graphics in retained mode and immediate mode. In addition to the APIs, the package defines a scene graph structure and a corresponding file format for managing and deploying 3D content efficiently, along with all other necessary data: meshes, scene hierarchies, material properties, textures, animation keyframes, and so on. This data is written to a file using content-creation tools and loaded into the API through the Loader class. The most important class is Graphics3D, because all rendering is done there. The World class serves as the root of the scene graph structure. Object3D is the base class of all objects that can be rendered or loaded from a file, as well as the place where animations are applied. Table 1 briefly describes all the classes in the javax.microedition.m3g package. Table 1: Classes in the m3g Package Class Description AnimationControllerControls the position, speed, and weight of an animation sequence. For example, it can be used to control the blinking and movement of a light in an animation application. AnimationTrack Associates a KeyframeSequence with an AnimationController and an animatable property, which is a scalar or vector variable that the animation system can update directly. Appearance A set of component objects that define the rendering attributes of a Mesh or a Spring3D. Background Defines how to clear the viewport. In retained mode, or when rendering a World, the Background object associated with the World is used. In immediate mode, a Background object is given a parameter to clear. If a Background object is not present, the default values specified in the T.E. SEM VI (IT): Programming for Mobile and Remote Computers
Prepared By: Diksha Kale

64 constructor are used. A scene graph node that defines the position of the viewer in the scene and the projection from 3D to 2D. The camera always faces towards the negative end of the Z axis (0, 0, -1). CompositingMode An Appearance component that encapsulates per-pixel compositing attributes. Fog An Appearance component that encapsulates attributes for fogging. Graphics3D A singleton 3D graphics context that can be bound to a rendering target. All rendering is done through the render() methods in this class. Group A scene graph node that stores an unordered set of nodes as its children. Image2D A two-dimensional image that can be used as a texture, background, or sprite image. There are two types: mutable images can be updated at any time; immutable images are fixed at construction time and cannot be changed later. IndexBuffer Defines how to connect vertices to form a geometric object. KeyframeSequence Encapsulates animation data as a sequence of time-stamped, vector-valued keyframes, each of which represents the value of an animated quantity at a specified instant. Can be associated with multiple animation targets. Light A scene graph node that represents different kinds of light sources, which are used to determine the color of each object, according to its Material attributes. Loader Downloads and deserializes graph nodes and node components, as well as entire scene graphs. Downloading ready-made pieces of 3D content from an M3G file is generally the most convenient way for an application to create and populate a 3D scene. Material An Appearance component encapsulating material attributes for lighting computations. Other attributes for lighting are defined in Light, PolygonMode, and VertexBuffer. Mesh A scene graph node that represents a 3D object defined as a polygonal surface. It represents a conventional rigid body mesh, and its subclasses MorphingMesh and SkinnedMesh extend it with capabilities to transform vertices independently of each other. MorphingMesh A scene graph node that represents a vertex-morphing polygon mesh. Node An abstract class for all scene graph nodes. There are five different kinds: Camera defines the projection from 3D to 2D as well as the position of the viewer in the scene. Mesh defines a 3D object consisting of triangles with associated material properties. Sprite3D defines a screen-aligned 2D image with a position in 3D space. Light defines the position, direction, colors, and other attributes of a light source. Group serves as a root for scene graph branches. Object3D An abstract base class for all objects that can be part of a 3D world. These include the world itself, other scene graph nodes, animations, textures, and so on. Everything in the API is an Object3D except Graphics3D, Loader, Camera T.E. SEM VI (IT): Programming for Mobile and Remote Computers
Prepared By: Diksha Kale

65 RayIntersection, and Transform. An Appearance component encapsulating polygon-level attributes, including settings related to back/front face culling, polygon winding, lighting computations, perspective correction, and shading. RayIntersection Stores a reference to an intersected Mesh or Sprite3D, and information about the intersection point. Strictly a run-time object, a RayIntersection is filled in by the pick() methods in the Group class, and cannot be loaded from a file by a Loader. SkinnedMesh A scene graph node that represents a skeletally animated polygon mesh. Sprite3D A scene graph node that represents a 2D image with a 3D position. This is a fast but functionally restricted alternative to textured geometry. It is rendered as a screen-aligned rectangular array of pixels with a constant depth. Texture2D An Appearance component encapsulating a 2D texture image and a set of attributes specifying how the image is to be applied on sub-meshes. The attributes include wrapping, filtering, blending, and texture coordinate transformation. Transform A generic 4x4 floating-point matrix representing a transformation. Transformable An abstract base class for Node and Texture2D, defining common methods for manipulating node and texture transformations. TriangleStripArray Defines an array of triangle strips. In a triangle strip, the first three vertex indices defines the first triangle. Each subsequent index together with the two previous indices defines a new triangle. For example, the strip S = (2, 0, 1, 4) defines two triangles: (2, 0, 1) and (0, 1, 4). VertexArray An array of integer vectors representing vertex positions, normals, colors, or texture coordinates. VertexBuffer Holds references to VertexArrays that contain the positions, colors, normals, and texture coordinates for a set of vertices. World A special Group node that is a top-level container for scene graphs. A scene graph is constructed from a hierarchy of nodes. In a complete scene graph, all nodes are ultimately connected to each other by a common root, which is a World node. PolygonMode

Creating 3D Applications An application that uses the Mobile 3D Graphics API for J2ME must be a valid MIDP application that follows the conventional MIDlet life-cycle. Use existing MIDP user interface classes such as Canvas and CustomItem to access the screen. To render the user interface, follow these steps: 1. 2. 3. 4. Create a Graphics3D object. Bind it to a 2D graphics object by linking the Graphics3D object to a 2D buffer. Render the desired World, Node, or sub-mesh. Release the graphics object, which will flush the rendered 3D view to the 2D buffer.
Prepared By: Diksha Kale

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

66
Conclusion:

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

67
Mixing 3D Graphics AnimationDemo import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.game.*; import javax.microedition.m3g.Graphics3D; import javax.microedition.m3g.Loader; import javax.microedition.m3g.World; import javax.microedition.m3g.Camera; public class AnimationDemo extends MIDlet implements CommandListener { private Display displayThis = null; private MyCanvas1 canvasThis = null; private Command commandExit = new Command("Exit", Command.ITEM, 1); public AnimationDemo() { super(); displayThis = Display.getDisplay(this); canvasThis = new MyCanvas1(); canvasThis.setCommandListener(this); canvasThis.addCommand(commandExit); } public void startApp() throws MIDletStateChangeException { canvasThis.init(); displayThis.setCurrent(canvasThis); canvasThis.start(); } public void pauseApp() { } public void destroyApp(boolean unconditional) throws MIDletStateChangeException { canvasThis.stop(); }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

68
public void commandAction(Command cmd, Displayable disp) { if (cmd == commandExit) { try { destroyApp(false); notifyDestroyed(); } catch (Exception e) { e.printStackTrace(); } } } }

class MyCanvas1 extends GameCanvas implements Runnable { private boolean myRunning = false; private Thread myPaintThrd = null; private Graphics3D myGraphics3D = Graphics3D.getInstance(); private World myWorld = null; private Camera myCamera = null; private long myWorldStartTime = 0; public MyCanvas1() { super(true); } public void init() { try { myWorld = (World) Loader.load("/pogoroo.m3g")[0]; myCamera = myWorld.getActiveCamera(); myCamera.translate(0, 0, -1.5f); myCamera.setOrientation(0, 0, 1, 0); } catch (Exception e) { e.printStackTrace(); } myWorldStartTime = System.currentTimeMillis(); } public void start() { myRunning = true; myPaintThrd = new Thread(this); myPaintThrd.start(); } public void stop() { myRunning = false; try { myPaintThrd.join(); } catch (InterruptedException ex) { }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

69
} public void run() { Graphics g = getGraphics(); long startTime; while (myRunning) { if (isShown()) { int keyStates = getKeyStates(); if ((keyStates & UP_PRESSED) != 0) { cameraForward(); } else if ((keyStates & DOWN_PRESSED) != 0) { cameraBackward(); } else if ((keyStates & LEFT_PRESSED) != 0) { cameraLeft(); } else if ((keyStates & RIGHT_PRESSED) != 0) { cameraRight(); } startTime = System.currentTimeMillis() - myWorldStartTime; myWorld.animate((int) startTime); myGraphics3D.bindTarget(g); myGraphics3D.render(myWorld); myGraphics3D.releaseTarget(); flushGraphics(); try { Thread.sleep(200); } catch (InterruptedException ie) { } } } // of while } private void cameraForward() { myCamera.translate(0f, 0f, 0.3f); } private void cameraBackward() { myCamera.translate(0f, 0f, -0.3f); } private void cameraLeft() { myCamera.translate(-0.3f, 0f, 0f); } private void cameraRight() { myCamera.translate(0.3f, 0f, 0f); } }

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

70

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

71

Quiz :
1.

What is MorphingMesh?

2.

What is IndexBuffer?

T.E. SEM VI (IT): Programming for Mobile and Remote Computers

Prepared By: Diksha Kale

You might also like