[转]J2ME MIDP Currency Converter Tutorial for NetBeans IDE 4.0

j2me MIDP Currency Converter Tutorial for NetBeans IDE 4.0

<script language=JavaScript type=text/javascript> </script> http://www.netbeans.org/kb/articles/tutorial-currencyconverter-40.html

Feedback

The Currency Converter application you will build in this tutorial shows you how to:

  • start a j2me MIDP project
  • code a working j2me MIDP application, or MIDlet, using the IDE
  • create project configurations to test the application's performance on two different device emulators

The Currency Converter application converts amounts from one currency to two others. You can choose to display three different currencies: euros, yen, or dollars. You can also enter a value in one currency to be converted into the other selected currencies.

There are three Java source code files for the sample application:

  • ConverterMIDlet.java. The code for the MIDlet class.
  • Converter.java. A MIDP form that defines the main screen of the application as it appears on a mobile device.
  • Currencies Selector.java. A MIDP list that maintains the currencies and rates.

The first part of this tutorial will show you how to quickly install, run, and test the Currency Converter application, which is available as a sample project included in the IDE. In the second part of the tutorial, you will create a new project and add code to create and test the application yourself.

This tutorial should take approximately an hour to complete.

Requirements

You must have NetBeans IDE 4.0 and the NetBeans Mobility Pack 4.0 installed before you can start j2me MIDP development. See the j2me MIDP Development Downloadpage for instructions on downloading and installing the complete environment.

Installing and Testing the Sample Currency Converter Project

In this first section, you will see how quickly you can install and run a sample project on two different emulator devices.

Creating the Project
  1. Choose File > New Project. Under Categories, select Samples > Mobile. Under Projects, select Currency Converter. Click Next.
  2. The Project Name and Location page sets the name and location of the project folder, and gives you the option of setting the project as the main project. Click Next to accept the defaults.
  3. The Platform selection page sets the default execution environment, the emulator platform, for the project. Note that the default emulator platform is the j2me Wireless Toolkit, and the default device is the DefaultColorPhone, a generic mobile device. Click Finish to complete the wizard.
    The Currency Converter displays in the Projects window.
Running the Project
  1. Choose Run > Run Main Project.
    The Currency Converter displays in the DefaultColorPhone device emulator.
  2. Now you're ready to test the application in the device emulator.
Testing the Application
  1. In the DefaultColorPhone screen, click the button under the word "Launch."
  2. Select the currency you want to convert by clicking the up and down arrow keys
    on the Select button. You can select Dollars, Euros, or Yen.
  3. Enter the currency amount to convert by clicking the emulator’s numeric keys.
    The application makes the conversion calculations and displays the results.
  4. Click the button underneath the word “Exit” to exit the application.
  5. Click the red button in the upper right corner to close the emulator.
Changing the Default Emulator Device

You can create different project configurations to test your MIDlet on different emulator platforms, or simply change the device for the default configuration.

  1. Choose File > "Currency Converter" Properties from the Main menu. In the Properties dialog, choose the Platform node. You can change the device for the default configuration.
  2. Click the Device dropdown menu and choose QwertyDevice. Click OK.
  3. Choose Run > Run Main Project Run the application again, and the application runs in the QwertyDevice emulator.

In the next part of this tutorial, you will start over, creating a new project. This will give you an opportunity to learn more about the code behind the application and how you can use the IDE to code and test your own applications.

Creating the Currency Converter Application

Creating the Project
  1. Choose File > New Project. Under Categories, select Mobile. Under Projects, select Mobile Application. Click Next.
  2. In the Project Name and Location page, name the project NewCurrencyConverter, and accept the default for Project Home. Leave the Set as Main Project check box checked, as you'll want this project to be your main project Click Next.
  3. Accept the defaults on the Platform page by clicking Finish.
    The NewCurrencyConverter application displays in the Projects window.

Creating the converterMIDlet.java MIDlet

  1. Choose File > New File. Under Categories, choose MIDP. Under File Types, choose MIDlet. Click Next.
  2. In the Name and Location page, Enter Currency Converter for the MIDlet name, ConverterMIDlet for the MIDP Class Name, and myconverter for the package name.

Coding the MIDlet

You can write the code for a MIDlet in one of two ways: either by directly entering code in the Source Editor or by using the IDE to add methods, fields, constructors, initializers, classes, and interfaces. Typically, you use the IDE to add new fields and methods to a class, or modify existing fields and methods, and then later fine-tune the code directly in the Source Editor.
The following procedure shows you how to use the tool and the Source Editor to enter or change code. However, to save time and effort, you can also copy the converter code from the example you installed.

Coding the ConverterMIDlet.java MIDlet
  1. In the Source Editor, add the following import statements to ConverterMIDlet.java:
    import java.io.*;
    import javax.microedition.rms.*;
  2. In the Projects Tab, expand the ConverterMIDlet node, right-click the ConverterMIDlet class and choose Add > Field.
    This next step will use the Add New Field dialog box to add the field storedDataStr to the MIDlet. The storedDataStr string contains the name of the RMS stored record.
  3. Complete the Add New Field dialog box:
    • Enter the name of the new field, storedDataStr, in the Name box and select
      its type, String, from the Type combo box.
    • In the Modifiers box, select the type of access for the field, private, from the
      Access combo box.
    • Check the other modifiers for the field, which in this case is static.
    • Set the initial value for storedDataStr to "ConverterData".
    • Click OK to close the dialog box.

    The field is added to the code in the Source Editor window.

  4. Add the following fields to the ConverterMIDlet.java class using the Source Editor.
    You can use the Add Field dialog box, copy the text from this page, or from the installed Currency Converter application, and paste it in the Source Editor. Be careful, however, not to change the package name from myconverter.

    public class ConverterMIDlet extends javax.microedition.midlet.MIDlet {
    private static String storedDataStr = "ConverterData"; public String[] currencies = new String[] { "US $", "Yen /u00a5", "Euro /u20ac" };
    public boolean[] selected = new boolean[] { true, true, true, true };
    public long[][] rates = {{ 1000000, 117580000, 911079 },
    { 8504, 1000000, 7749 }, { 1097600, 129056000, 1000000 }};
    private RecordStore storedData;
  5. Add the following code to the method startApp(). This method is called when the application is started. It loads all the data (currencies, selected currencies, and exchange rates) from persistent storage and initially displays the Converter form. The method should look like this:
    public void startApp() {
    try { storedData = RecordStore.openRecordStore(storedDataStr, true); if (storedData.getNumRecords() > 0) { DataInputStream in = new DataInputStream(new ByteArrayInputStream(storedData.getRecord(1)));
    try {
    int size = in.readInt();
    currencies = new String[size];
    selected = new boolean[size];
    rates = new long[size][];
    for (int i=0; i<size; i++) {
    currencies[i] = in.readUTF();
    selected[i] = in.readBoolean();
    rates[i] = new long[size];
    for (int j=0; j<size; j++) {
    rates[i][j] = in.readLong(); }
    } in.close();
    } catch (IOException ioe) {
    }
    }
    } catch (RecordStoreException e) {
    }
    notifySettingsChanged();
    }
  6. The destroyapp() method is called when the application is finished, or destroyed. Add the following code to complete the destroyApp() method:
    public void destroyApp(boolean unconditional) {
    try {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bytes);
    try {
    out.writeInt(currencies.length);
    for (int i=0; i<currencies.length; i++) {
    out.writeUTF(currencies[i]);
    out.writeBoolean(selected[i]);
    for (int j=0; j<currencies.length; j++) {
    out.writeLong(rates[i][j]);
    }
    }
    out.close();
    if (storedData.getNumRecords() > 0)
    storedData.setRecord(1, bytes.toByteArray(), 0, bytes.size());
    else
    storedData.addRecord(bytes.toByteArray(), 0, bytes.size());
    } catch (IOException ioe) {
    ioe.printStackTrace();
    }
    } catch (RecordStoreException e) {
    e.printStackTrace();
    }
    notifyDestroyed();
    }
  7. Add the following three new methods:
  • showSettings()
    This method creates and displays the CurrenciesSelector list.
      public void showSettings() {
         Display.getDisplay(this).setCurrent(new CurrenciesSelector(this));
      }
  • notifySettingsChanged()
    This method displays a new Converter form after the settings are changed.
     public void notifySettingsChanged() {
    Display.getDisplay(this).setCurrent(new Converter(this));
    }
  • longconvert()
    This method performs the currency conversion. The input value, frval, is multiplied by the exchange rate stored in the rates table and divided by 1,000,000. The fridx and toidx values are the indexes of the source and target currencies.
    public long convert(long frval, int fridx, int toidx) {
    return (frval * rates[fridx][toidx]) / 1000000;
    8. Save the ConverterMIDlet by choosing File > Save.

Creating a MIDP Form

Now that you have completed the code for the MIDlet, you will create the application’s graphical interface. A form is a Java class that can contain an arbitrary mixture of items, including images, read-only and editable text fields, editable date fields, gauges, choice groups, and custom items. The form you create here will specify a text box for each selected currency and specify the ItemStateListener()method to monitor and reflect typed values and perform conversions.

Coding the Converter.java MIDP Form

  1. In the Projects window, right-click the myconverter package. Choose File > New File/Folder.
    The New File wizard opens.
  2. Under Categories, expand MIDP, then expand MIDP Forms. Under File Types choose MIDP Form. Click Next.
  3. In the Name and Location page, enter Converter for the class name. Click Finish.
    A MIDP form is created and added to the myconverter package.
  4. In the Source Editor, add the following fields to the code below the public class Converter declaration:
    private ConverterMIDlet midlet;
    private int[] translate;
  5. Add the following code to complete the constructor, so it looks like the sample below:
    public Converter(ConverterMIDlet midlet) {
    super("Currency Converter"); this.midlet = midlet;
    this.translate = new int[midlet.currencies.length];
    int current = 0;
    for (int i=0; i<translate.length; i++) {
    if (midlet.selected[i]) {
    translate[current++] = i;
    append(new TextField(midlet.currencies[i], "", 12, TextField.NUMERIC));
    }
    }
    try {
    // Set up this form to listen to command events
    setCommandListener(this);
    // Set up this form to listen to changes in the internal state of its interactive items
    setItemStateListener(this);
    // Add the Currencies command
    addCommand(new Command("Currencies", Command.OK, 1));
    // Add the Exit command
    addCommand(new Command("Exit", Command.EXIT, 1)); } catch(Exception e) {
    e.printStackTrace();
    } }
  6. Add the following code to complete the method commandAction(), so it looks like the sample below:
     public void commandAction(Command command, Displayable displayable) {
    if (command.getCommandType() == Command.EXIT) {
    midlet.destroyApp(true);
    } else if (command.getCommandType() == Command.OK) {
    midlet.showSettings();
    } }
  7. Add the following code to complete the itemStateChanged() method, so it looks like the sample below:
    public void itemStateChanged(Item item) {
    try {
    long value = Long.parseLong(((TextField)item).getString());
    int from = 0;
    while (get(from) != item) from++;
    from = translate[from];
    for (int i=0; i<size(); i++) {
    int to = translate[i];
    if (from != to) {
    ((TextField)get(i)).setString(String.valueOf(midlet.convert(value, from, to)));
    }
    }
    } catch (NumberFormatException nfe) {
    for (int i=0; i<size(); i++) {
    ((TextField)get(i)).setString("");
    }
    }
    }
    This completes the Converter.java form file.

Creating a MIDP List

The final piece of the Currency Converter application is the CurrenciesSelector.java list file, which defines the currencies that can be
selected for display.

Coding the CurrenciesSelector.java MIDP List

  1. In the Projects window, right-click the myconverter package. Choose File > New File/Folder.
    The New File wizard opens.
  2. Under Categories, expand MIDP, then expand MIDP Forms. Under File Types choose MIDP List. Click Next.
  3. In the Name and Location page, enter CurrenciesSelector for the class name. Click Finish.
    A MIDP list file is created and added to the myconverter package.
  4. After the line public class CurrenciesSelector extends List implements CommandListener {, declare a field:
    private ConverterMIDlet midlet;
  5. Add the following code to complete the constructor, so it looks like the sample below:
       public CurrenciesSelector(ConverterMIDlet midlet) {
    super("Select Currencies", List.MULTIPLE, midlet.currencies, null);
    this.midlet = midlet;
    setSelectedFlags(midlet.selected);
    try {
    // Set up this list to listen to command events
    setCommandListener(this);
    // Add the Save command
    addCommand(new Command("Save", Command.OK, 1));
    } catch(Exception e) {
    e.printStackTrace();
    }
    }
  6. Add the following code to complete the method commandAction(), so it looks like the sample below:
        public void commandAction(Command command, Displayable displayable) {
    if (command.getCommandType() == Command.OK) {
    getSelectedFlags(midlet.selected);
    midlet.notifySettingsChanged();
    }
    }
    This completes the CurrenciesSelector.java list file.

Testing Your Application

Now that you have created your application, you can test it with different emulator devices, as you did with the sample Currency Converter project you first installed. However, instead of switching the emulator device in the default configuration, this time you will create a second project configuration for the QwertyDevice device emulator.

Creating a New Project Configuration

  1. Choose File > "NewCurrencyConverter" Properties.
  2. Click the Manage Configurations button.
    The Project Configuration Manager opens.
  3. Click the Add Button.
    The Add Configuration button displays.
  4. Name the new configuration QwertyDevice. Click Ok.
  5. Click Close to close the Project Configuration Manager.

You now have a second configuration, QwertyDevice, that has the same properties as the DefaultConfiguration.

Changing the Device Property
  1. While still in the Project Properties, choose Platform from the tree menu in the left pane of the window.
  2. If it QwertyDevice is not shown as the active project configuration, choose it from the Project Configuration dropdown menu.
  3. So that you can choose new values for this configuration, Uncheck the "Use Values from DefaultConfiguration" check box.
  4. Choose QwertyDevice from the Device dropdown menu. Click OK.
Running the Application on Both Configurations
  1. Make sure that the Configuration dropdown menu on the toolbar lists DefaultConfiguration as the active project configuration.
  2. Choose Run > Run Main Project.
    The Currency Converter opens in the DefaultColorPhone Device emulator screen.
  3. Choose QwertyDevice from the Configuration dropdown menu in the toolbar.
  4. Choose Run > Run Main Project.
    The Currency Converter opens in the QwertyDevice Device emulator screen.
  5. Now you can test and compare the application's performance on different devices at the same time.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
J2MEJava 2 Platform, Micro Edition)是由Sun Microsystems开发的一种Java平台,专门用于在移动设备上运行应用程序。MIDP(Mobile Information Device Profile)是J2ME的一个子集,它定义了在移动设备上运行的应用程序的规范和功能。而MIDP 2.0则是MIDP的第二个版本。 MIDP 2.0增加了许多新的功能和改进,使得开发者能够创建更强大和多样化的移动应用程序。它提供了一个可扩展的用户界面,包括支持图形、文本和交互控件。此外,MIDP 2.0还引入了支持浏览器和网络协议的API,使开发者可以轻松地在移动设备上进行网上浏览、发送和接收数据。 MIDP 2.0还加强了网络通信的能力,引入了新的网络连接API,如HTTP和Socket连接。这使得开发者能够通过互联网或网络进行数据交换和通信。同时,它还支持存储和管理数据的持久化功能,允许应用程序在重启后保留数据。 除了以上功能,MIDP 2.0还提供了音频和视频支持,使开发者能够创建媒体相关的应用程序。开发者还可以利用MIDP 2.0的游戏API创建游戏应用程序,包括图形、动画和触发事件等功能。 总之,J2ME MIDP 2.0是一种用于移动设备的Java平台和规范,提供了丰富的功能和API,使开发者能够创建各种各样的应用程序,包括用户界面、网络通信、数据存储、音频视频和游戏等。它的出现大大促进了移动应用程序的发展和普及。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值