J2ME Wireless Communication Programming Getting Started Yin Huacheng Appendix Article
With the advent of mobile phones that support Java software, the program applied to the phone is no longer a dream. This article will introduce the reader how to use J2ME to develop mobile phones and mobile devices.
I. Basics: J2ME Architecture Detailed 1. What is J2ME J2ME, Java 2 Micro Edition, which is part of Java 2, and J2SE, J2EE. J2ME is a highly optimized Java operating environment, applied to a large number of consumer electronics, such as Cellular Phones, Screen Phones, Digital Set-Top Boxes (Digital Top Box), Car Navigation Systems ( Automotive-oriented system), etc., and also widely used in mobile communication equipment, such as mobile phones, two-way paging, smart cards, Personal Organizer and Palmtop, and so on. J2ME technology ports the Java language to the platform-independent characteristics to small electronic devices, allowing mobile wireless devices to share applications.
2.J2ME architecture and configuration (1) J2ME architecture
The J2ME architecture is based on the device's series and category, and a category defines a particular type of device. Mobile phones, pagers, and personal computer notepads are separate categories. A series of devices that have a few categories of devices that have similar requirements for memory and processing capabilities. Mobile phones, pagers, and personal computer notepads are a series of devices that occupy small resources. Figure 1 defines the relationship between the series and categories of the device in the J2ME environment.
In addition, in order to support the flexibility and customizable deployment required by the resource restricted device, people are designed to be modular and scalable. J2ME technology defines this module and scalability in a complete application running model, and four software layers in the model are constructed on the host operating system of the device. The architecture of J2ME is shown in Figure 2.
Java Virtual Machine Layer: It is an implementation of the Java virtual machine, which is customized for host operating systems for specific devices, and supports a specific J2ME configuration.
Configuration Layer: The configuration layer defines the minimum set of Java class libraries available on the Java virtual machine and the specific category device. To some extent, a configuration defines the commonality of the Java platform function section and libraries, which can assume that these features and libraries are available on all devices belonging to a particular class.
PROFILE LAYER: The frame layer defines the minimum set of application programming interfaces (APIs) available on a particular series of devices. The frame is implemented on a specific configuration. The application is written for a particular framework, so it can be ported to any device that supports the framework. A device can support multiple frames. User and application vendors see the most of this layer.
MIDP (Mobile Information Device Profile layer: Mobile Information Device Framework. It is a collection of Java API, which handles issues such as user interfaces, persistent storage and networking.
(2) J2ME configuration
It is known that the J2ME assembly surrounds a center, which are called "configuration". They are used for special classes for consumer electronics and embedding equipment. At present, J2ME defines two "configuration", which supports different device objects due to its ability to process computing.
Connected Limited Device Configuration (CLDC, Limited Connection Device Configuration): This "Configures" Defines the Java application interface and technology that supports handheld devices. Such as mobile phones, handheld computers, etc.
Connected Device Configuration (CDC, Connection Device Configuration): This "Configuration" supports the application interface of "inserted wall" devices such as set-top boxes.
The above two "configuration" are differentiated in the ability of their applicable devices: the processor capability of the CLDC device is limited (compared to the desktop), and the memory size is generally between 128KB to 512KB, and the CDC system is different, It may have a 32-bit or 64-bit processor, as well as a limited storage capacity, but its lower limit is more than 512KB. The principle that they follow is that each different functional hardware device will be supported by different virtual machines.
3. Although the "Configuration" provides the smallest Java platform for a set of generic devices, developers are interested in designing applications for individual equipment, and when they use "configuration" to develop, then write Applications will definitely be lacking. "Configuration" must meet the minimum requirements of all devices, while user interfaces, input mechanisms, and data persistence have a high degree of equipment, each device has its own method, which is often not "configuring" minimum. The range is required.
Now, five known briefings have been specified. Each brief watch is to improve the deficiency of the configuration.
(1) MIDP brief watch
MIDP (Mobile Information Device Profile, mobile information device "is the first profile, which adds CLDC configuration, and provides application semantics, user interface, persistent memory, network, and timing for mobile phones. Of a dual channel call and other radio.
(2) PDA brief watch
Palm is the leader of the development of PDA brief mesh specification, which improves CLDC configuration. It will be alternative to KJAVA class packages in a considerable period of time. Java specification It is recommended that the brief table should at least provide 2 core functional fragments, namely user interface display kits, suitable for "limited size and depth display", and the other is a persistent data memory mechanism. The display kit should be a subset of the Abstract Window Toolkit, while the persistent mechanism will provide simple data storage for applications, data, configuration / environment information.
(3) Foundation brief watch
The task of the Foundation brief is to serve as a basic profile, which is convenient for future developments to provide a brief watch with graphical user interfaces, networks. In addition to the basic profile, Foundation briefs also provide full network support, no matter whether there is a graphical user interface.
(4) Personal
Under the current requirements of the current specification, the Personal briefly provides the next generation of Personal Java environments. This brief address provides Internet connectivity and Web fidelity and a GUI that can run Java Applets.
(5) RMI brief watch
We know that the CDC is configured to share, fixed network connection information devices provide the smallest Java environment. This brief mesh will assist in providing better network connectivity by providing Java to Java's RMI.
Second, Getting Started: MIDP Brief Sheet Application Example We introduced the basics of J2ME, and also mentioned the role of the MIDP brief watch. Now let's see how to develop applications with J2ME and MIDP.
Note: The Java app written in accordance with the MIDP brief watch and CLDC configuration specification, we call it MIDLET.
1.MIDP / CLDC API Overview Since the MIDP / CLDC API will run on a single performance, some of the functions of Java are removed or modified.
(1) MIDP class library
As mentioned above, Sun defines a MIDP layer above the CLDC configuration to provide support for user interface (User Interface, UI), permanent storage medium, and networks. Below, let's take a look at the MIDP class library.
MIDP is composed of four javax.microedition packets, including:
Javax.microedition.rms: About permanent storage media (RMS Record Management System).
Javax.microedition.midle: Defines the MIDlet framework, as well as the MIDlet and the environment interaction. Javax.microedition.IO: Supply network support.
Javax.microedition.lcdui: About User Interface (UI is divided into two APIs with High Level and Low Level).
(2) component
MIDP brief mesh and CLDC configuration combination provide a complete development environment for applications on creating mobile phones and simple two-way paging.
The core of the MIDP frame is a MIDlet application. This application inherits the MIDlet class to allow application management software to control the MIDlet, from the application description attribute, and notify status changes. All MIDlets inherit the MIDlet class-runtime environment (Application Manager) and the interface between the MIDlet application code. The MIDLET class provides an API for calling, pause, restarting, and terminating the MIDlet application. Application Management Software can manage multiple MIDlet activities in the runtime environment. In addition, MIDlet can issue some status changes and notify these changes to the application management software.
A complete collection of the MIDP API class can be divided into two categories:
MIDP API for user interfaces: Designing these APIs to be able to intermove with the user with a series of screens, and each screen displays the right amount of data to the user. These APIs allow applications to determine what requests from the next screen display, what, calculate, and use network services.
MIDP APIs for processing databases: These APIs are responsible for organizing and operating device databases, which consists of persistent information from multiple calls in MIDlets. The underlying CLDC API is used to process strings, objects, and integers. A subset of Java 2 API is also provided for processing I / O and network communication.
(3) User Interface Design (UI)
MIDP API despite maintenance of a limited frame, it still provides a complete collection of user interface elements. The following is the most important UI element:
Alert: The information used to display an exception or an error on the screen.
Choice: It is used to achieve selection from a set number of options.
Choicegroup: Provides a set of related options.
Form: As a container of its user interface element.
List: Provide an option list.
StringItem: Only the string is displayed.
Textbox: Allows the user to enter and edit the screen display of the text.
TEXTFIELD: Allows users to enter and edit text. Multiple TextField can be placed in an Form.
DateField: It is an editable component that represents date and time information. Datefield can be placed in Form.
Ticker: Scroll-up display for text.
(4) Equipment database management
The MIDP brief mesh provides a set of classes and interfaces for organization and operating equipment database: RecordStore, RecordComparator, and Recordfilter. RecordStore consists of a large number of records, which remains lasting when multiple calls of MIDlets. Compare the records in the RecordStore, or draw a number of group records from the RecordStore, which is the function provided by the RecordComparator and Recordfilter interface.
2. The configuration programming environment is different from other programming languages. The J2ME programming environment is first configured before developing a J2ME program.
(1) Software preparation
Before developing a MIDlet, you need to download:
Java Development Kit (JDK), 1.2 or more.
Connected, LIMITED Device Configuration (CLDC).
Mobile Information Device Profile (MIDP).
(2) Software installation JDK installation: JDK has default the directory for installation files, of course, you can also choose the path to be installed in your own. Such as E: /JDK1.3.
Installing a CLDC configuration: Download to the CLDC software to the hard disk, the author's recommended path is E: / J2ME. After decompression, the structure of the E: / J2ME path is as follows:
E: / J2ME
|
J2ME_CLDC
Installing the MIDP: Same up, unzip the MIDP software to the hard disk directory E: / J2ME, now the directory structure is as follows:
E: / J2ME
|
J2ME_CLDC
MIDP-FCS
(3) Configuration software
The PATH environment variable is the Windows operating system to locate the executable program. We need to update the path to the path to the Java compiler and the CLDC, the MIDP program.
Update JDK PATH: If you are in a Windows NT / 2000 environment, double-click the System icon in the Control Panel, where you click the Advanced tab, click the Environment Variable button, appear In the "System Variable" list in the Dialog box, you find and double-click PATH, add the / bin directory of the JDK installation path at the end of the "variable value" in the previous dialog. Suppose you install JDK is a 1.3 version and select the default installation path, this example is E: /JDK1.3. If it is in a Windows 98 environment, please add the following two lines in the C: /autoexec.bat file.
SET PATH = E: /JDK1.3/bin;% PATH%
Set classpath = .;
Update CLDC Path: You also need to update your PATH environment variable to point to the directory where the CLDC executable file is stored. Add it to the PATH as described above:
E: / J2ME / J2ME_CLDC / BIN
Update the MIDP path: Update the Path environment to indicate the directory where the MIDP executable is stored, which is used to test the mobile phone simulator for the MIDlet.
Add it to the path as described above, here is E: / J2ME / MIDP-FCS / BIN.
Let's update the ClassPath environment variable. ClassPath tells the Java compiler to where to search for class libraries that are not included in the JDK platform itself, in this case, we need to update ClassPath to point to the MIDP class. You also need a reference (".") Of the current directory ("."), As part of the ClassPath, update ClassPath: ClassPath = E: / J2ME / MIDP-FCS / CLASSES ;.
Note: The last point "." Indicates the current working directory.
Finally, let's add the Screen_Depth environment variable. The MIDP contains a mobile device simulator for testing MIDlet, which can operate in colored mode, and can also run the grayscale gradient mode composed of black and white two-color. To specify the number of colors, you can add environment variables Screen_Depth. Such as crien_Depth = 8. Adding this environment variable is similar to how to process the Path and ClassPath variables.
The corresponding relationship between Screen_Depth values and colors is given in the table below.
Value color numerical color number
1 2 2 4
4 16 8 256
3. Write the code Now we write the "Hello World!" Application to learn about the structure of the J2ME program and write methods, here, the program name is Helloj2me, the program code is as follows:
Import javax.microedition.midlet. *;
Import javax.microedition.lcdui. *;
Public Class Helloj2me Extends Midlet ImmancellListener
{
Private Display Display; Private Textfield Tfhello;
Private command cmexit;
PRIVATE FORM FMMAIN;
Public helloj2me ()
{
Display = display.getdisplay (this);
// Create a master form
Fmmain = New form ("Helloj2ME");
// Create "EXIT" button
CMEXIT = New Command ("exit", command.screen, 1);
// Create a single line that can accommodate 15 characters
Tfhello = New TextField ("Text", "Hello World!", 15, TextField.Any;
// Add control to the main form
Fmmain.addcommand (cmexit);
FMMain.Append (Tfhello);
Fmmain.setCommandListener (this);
}
As we see, the Helloj2me program extends the MIDP basic application MIDET class and imports two package namespaces: javax.microedition.midlet and javax.microedition.lcdui. The former includes the MIDlet base class of the application, while the latter provides a set of Swing GUI element supplies for use.
The MIDLET class provides three abstract methods for the device application manager to communicate with its run. As long as the application is activated, the STARTAPP method will be called immediately after the constructor is executed, not when the application is initially started. The application will change multiple times between activity and inactive states during one run, so you don't have to write initialization code that is running separately, because such code is likely to perform many times. For this purpose, a constructor should be used to complete the same function.
The manager is called after the application is shut down, the DestroyApp method is called. The STARTAPP method is different that this method is only called once within the application survival period, so writing clearing code in this method is safe. In fact, since the MIDP does not include a Finalize function for an object, you have to perform a clear function at the above method. At the same time, since the typical mobile device is shorter than the standard platform, it is often turned off or reset by the user. So you can't really expect DESTROYAPP to send a big usage.
The final abstraction method is pauseApp. The main role of this method is to issue such a notice. Since the user is converted to other applications or uses a feature of the device that causes the application to temporarily stop the application. Since most mobile devices lack the ability to perform multitasking, this type of situation is entirely possible. So in this method, you should encode all resources. Once the application is re-developed, the application manager will call the StartApp method again.
Third, advanced article: Wireless message transfer system analysis For the particularity of mobile software, we need to understand the basic principles of "wireless messaging". Below we will focus on several commonly used wireless messaging methods.
1.GSM SMS Service and Community Broadcasting Service Wireless Messages The Thought of Wireless Messages Broadcasting the New Prospects for J2ME. J2ME applications supported by wireless messages can access wireless communication resources independently of the platform, such as the global mobile communication system (GSM) network (a mobile telephone system allowing transnational communication) (SMS) ) And cell broadcast service (CBS).
(1) GSM SMS Service (SMS)
SMS is the transfer of a short text message between a mobile phone, a fax machine and an IP address in a GSM network. The transmitted message must not exceed 160 letters, numeric characters, and does not include image or graphics. The main features of this service are rapid, cheap and guaranteed to reach the target user.
Once the message is sent, it will be received by the SMS Service Center (SMSC) that must then send the message to the appropriate mobile device. To do this, SMSC sends SMS requests to home location registers to find roaming users. Once the HLR receives the request, it will respond to the SMSC in the user's status (such as 1. Inactivity or active, 2. Roaming location). If the response is inactive, the SMSC will retain the message for a while. When the user uses its device, the HLR sends an SMS notification to the SMSC, while the SMSC attempts to transmit. The SMSC sends a message to the GSM message sending system in a short message delivery point pair point-to-point format. The system paging the device and send a message if the device responds. At the same time, SMSC will receive verification, that is, the message has been received by the end user, and then classs the message as sent, and will no longer try to send it.
(2) GSM Community Broadcast Service
The GSM cell broadcast service allows messages to be sent to each mobile station located in a particular cell, such as mobile phones, fax machines, and IP addresses. Duplicate the cell broadcast message in a period of time, so that the MS that enters the cell after the first transmission can also receive the message. You can send up to 15 pages of data in the form of binary data or ASCII text, with up to 93 characters per page, and the test device only provides support for ASCII messages. The cell broadcast message is classified according to the topic, and the channel number, message code, update number, and language are assigned to each message.
Channel number: Identify the head number of the message theme (such as the 'Meteorological Report' or 'Traffic Information').
Message code: Identifies a specific message so that when the message code received by MS is the same as the previously received, this is a repetitive message, and it is not displayed to the user.
Update Number: Specific versions used to identify messages.
Language: Indicates the language used by the message. Changing this parameter does not make the original text of the message to be translated.
2. Wireless message transfer system resolution briefly, we can consist of a wireless message transfer system as a three-layer architecture, consisting of interface layers, implementation layer, and transport layer (Transport Layer).
The interface layer constitutes a set of universal messaging interfaces that are independent of all messaging protocols. These interfaces provide basic definitions of messages, define the basic functions of sending and receiving messages, and providing mechanisms to notify the MIDlet application to enter messages.
The implementation layer contains such a class that implements each interface layer to access wireless messaging, such as SMS or CBS functions on the GSM mobile device. For example, in terms of SMS, this layer provides a message connection implementation for SMS messages, and implementation of SMS messages with text or binary properties. The realization layer also performs message segmentation and parallel for the underlying protocol. Then, the MIDlet can specify a message to be split into several segments in MessageConnection.
The transport layer contains such a class that actually implements protocols that transmit messages to mobile devices.
3. General Message Passing API - Javax.wireless.MESSAGING
This API is defined by a javax.wireless.Messaging package that defines all interfaces that are used to send and receive wireless messages.
Message: Provide a basic definition of messages, act as a container to accommodate the address of the message, pay the payload, and the flag of sending and blocking. It is a super interface of TextMessage and BinaryMessage, which is a message object with a text payload attribute and a binary payload attribute. The structure of Message is shown in Figure 3.
MessageConnection: Provides the basic functionality of receiving and sending messages. It contains a method of sending and receiving a message, a factory method for creating a new Message object and a calculation that sends a number of underlying protocol segments required for a specified Message object. This class can be instantiated by calling Connector.Open ().
In the client mode connection, only the message can be sent. Create a client mode by passing a string of the identification destination address to the Connector.Open () method. This method returns the MessageConnection object.
ClientConn = (MessageConnection) Connector.Open ("SMS: // 186436309999: 5000");
In the server mode, you can send or receive messages. The server mode is created by passing the string identifying the local host upper endpoint (depends on the protocol, for example, port number) to CONNECTOR.OPEN () method.
ServerConn = (MessageConnection) Connector.Open ("SMS: //: 5000");
MessageListener: It provides a basic mechanism to notify the MIDlet application. When new to messages can be read, it allows MIDlet to receive a callback.
(1) SMS service API
J2ME's com.sun.midp.io.j2me.sms package provides an API for SMS service messaging systems, and allows MIDlet to access SMS features on GSM mobile devices.
This package mainly includes two main components of MessageObject and Protocol for supporting the transmission and reception of SMS messages.
MessageObject: Used for SMS messages.
In the realization layer, the javax.wireless.Messaging.Message interface is implemented as a buffer. MessageObject processes the creation of the message buffer and input / output operations outside of the buffer. In addition, it has two subclasses, namely TextObject and binaryObject. These classes implements SMS messages with text or binary payload.
Protocol: It implements a message connection that is required to send the SMS message. In this process, it checks all running configuration parameters and handles an exception related to invalid URL syntax, security violation, I / O violations, and invalid parameters. Protocol also handles messages and reception using packets or serial port connections.
(2) Community broadcast messaging API
J2ME's com.midp.io.j2me.cbs package provides an API for cell broadcast messaging systems, and allows MIDLLET to access CBS features on GSM mobile devices.
The main component of the package com.sun.midp.io.j2me.cbs.Protocol supports reception of CBS messages. The difference between CBS and SMS is that the URL connection string does not support the specified host, and it is only used for inbound protocols. MIDlets with CBS capabilities can receive messages, but they cannot send them.
Fourth, an example analysis section: A J2ME message delivery application Let's introduce a sample program WMASERVER to introduce how J2ME implements messaging? The main function of the sample program is: Waiting for the entry SMS message, then display them on the phone screen. The javax.microedition.lcdui package provides a set of functions for implementing the user interface of the application.
The WMASERVER MIDLET is connected to the connector.open () method by passing the endpoint (depending on the identifier of the protocol, such as a port number) to the Connector.Open () method. In order to receive a notification of entering messages, the MIDlet registers a MessageListener object at the MessageConnection instance serverConn.
ServerConn.setMessageListener (MessageListener ML); it also implements notifyIncomingMessage () in the MessageListener interface. When entering the message reaches the MessageConnection, the NotifyInComingMessage () method is called. The application must use the MessageConnection's Receive () method to retrieve the message.
The WMASERVER application reads text or binary payload data from the entry message, and then stores it in a string object.
Public void NotifyIncomingMessage (MessageConnection CONN) {
Message msg = NULL;
// Try Reading (Maybe Block for) A Message
Try {
Msg = conn.receive ();
}
Catch (Exception E) {
// Handle Reading ErrorS
System.out.println ("ProcessMessage.Receive" E);
}
// process the received message
IF (MSG InstanceOf TextMessage) {
TextMessage TMSG = (TextMessage) MSG;
Msgreceived = tmsg.getpayloadText ();
}
Else
{
// Process Received Message
IF (MSG InstanceOf BinaryMessage) {
BinaryMessage Bmsg = (binarymessage) msg;
Byte [] data = bmsg.getPayloadData ();
// Handle The Binary Message ...
Msgreceived = data.toString ();
}
}
When the connection resource and associated listener objects must be released, the application provides the destroyApp () method.
Public void destroyApp (boolean unconditional) {
Try {
IF (ServerConn! = null) {
ServerConn.setMessagelistener (NULL);
ServerConn.close ();
}
}
Catch (IOException E) {
// Handle The Exception ...
E.PrintStackTrace ();
}
V. Practice: Writing the "Capture Keyboard Enter the ASCI II code" program through the previous introduction, we have an intuitive understanding of J2ME. Below we will further explain the method of writing a mobile phone application by writing a specific example program. This example is applied to Motorola 388 mobile phones, and after the routine is completed, the ASCI II code input to the keyboard will be captured.
1. About development tools Motoj2sdk is a custom command-made development kit customized command line, including CodeWarrior, JCREATOR, and so on.
Wireless Handheld Device (MDIP) Easy Development Kit (MDIP installation method has been described above).
Java 2 SDK 1.3 is a must-have, it provides a platform for development, testing, and running a Java program (installation method sees in any).
Development Environment I recommend using JCREATOR.
2. JCReater Motoj2sdk configuration and use This is a must and is extremely important. If the configuration is incorrect, your program will not be able to run. We assume that all the installation paths of all development tools are as follows:
JCREATOR: D: / Program Files / XINOX Software / JCREATOR LEMOTOJ2SDK: D: / MOTOJ2SDK
JDK: D: /JDK1.3.1
Before starting configuration, we must first activate the simulated environment. Run d: /motoj2sdk/gener.bat, and select the phone model, select the language, select Normal, and then click "Create". After completing the above work, we can configure it.
The first step, select Configure → Options → JDK PROFILES.
Note: You must create a new Profile and SELECT "D: /JDK1.3.1".
Change the name to "J2ME 388"; add class PATH Change to "D: / Motoj2SDK / LIB"; add documentation path change to "D: / Motoj2sdk / DOCS".
Step 2, select Configure → Options → JDK Tools.
Select Complier, select the And Edit IT, change parameters to "-O -BootClassPath D: / Motoj2SDK / LIB $ [JavaFiles].
Step 3, select Configure → Options → Tools.
Click the "New" button, select DOS Command to create a new name "preveriFier" DOS Command and change arguments to "d: /motoj2sdk/bin/preverifier.exe -classpath" d: / motoj2sdk / lib "-d. "; Change Initial Directory to" $ [prjDir]. "
In the fourth step, press the above method to create a new name "Run Emulator" DOS Command.
Change arguments to "Java-D java.library.path = d: / motoj2sdk / lib -classpath" d: /motoj2sdk/bin/emulator.jar ";" D: /motoj2sdk/configtool.jar "com.mot.tools .j2me.emulator.emulator -classpath $ [prjDir]; "D: / motoj2sdk / lib" -DeviceFiled: /motoj2sdk/bin/resources/device.props javax.microedition.midlet.appmanager $ [curclass] -JSA 1 1 "
Change Initial Directory to "D: / Motoj2SDK / BIN".
The fifth step, the same name "Create Jar" DOS Command in accordance with the above method.
Change arguments "" $ [javahome] /bin/jar.exe "CVFM $ [prjName] .jar
Meta-inf / manifest.mf * .class * .png ".
Change Initial Directory to "$ [prjDir]."
3. Write instance code to select "Empty Project" to create a new project and name myj2. JCReater will automatically generate subdirectory "Myj2" in your working directory. Select "Java File" to create a new Java file. Write the following code:
Import javax.microedition.lcdui. *;
Import javax.microedition.midlet. *;
Public class test extends Midlet imports commandlistener {private keyeventsdemocanvas mycanvas;
PRIVATE DISPLAY MYDISPLAY;
Private Command Okcommand = New Command ("OK", Command.ok, 1);
MYJ2 () {
MyDisplay = display.getdisplay (this);
Mycanvas = new keyeventsdemocanvas ();
Mycanvas.addcommand (OkCommand);
Mycanvas.setCommandListener (this);
}
Public void CommandAction (Command C, Displayable S) {}
Protected void startapp () throws midletStateChangeException {
mydisplay.setcurrent (Mycanvas);
}
protected void pauseapp () {}
Protected Void DestroyApp (Boolean Unconditional) {}
Class keyeventsdemocanvas extends canvas {
Public final int background_color = 0xfffff;
Public final int forground_color = 0x000000;
Private int laastkey;
Public void paint (graphics g) {
g.setcolor (Background_color);
G.fillRect (0, 0, getWidth (), getHeight ());
g.setcolor (foreground_color);
G. DrawString ("Press A Key!", 0, 0, Graphics.top | Graphics.Left);
IF (LastKey! = 0) {
g.drawstring ("Key Code:" LastKey, 0, g.GetFont (). getHeight (),
Graphics.top | graphics.Left);
Try {
g.drawstring ("Action:" getGameAction (LastKey), 0,
2 * g.getfont (). GetHeight (),
Graphics.top | graphics.Left);
g.drawstring ("Key Name:" getKeyName (LastKey), 0,
3 * g.getfont (). GetHeight (),
Graphics.top | graphics.Left);
} catch (exception e) {
}
}
}
Public void keypressed (int keycode) {
LastKey = keycode;
Repaint ();
}
Public void keyreated (int keycode) {
System.out.println ("Key Repeated Keycode);
}
}
Save the file and name myj2.java. Click the "Add File" button in the Project, select the Myj2.java file you just now, the compiler, and run it.