## Beginning Java ME: A Simple Mandelbrot Viewer

Version 3.0 of the Java ME SDK from Sun makes it very easy to start developing Java applications for mobile devices. The SDK comes with a full-fledged (and surprisingly usable) IDE, as well as a suite of emulators and example applications, all of which allows you to pick up and start writing your own apps in no time. I’ve always wanted to develop a few small applications that I could run from my phone, so I thought this might be a good time to start.

My first idea was to develop a very basic Mandelbrot set renderer and zoomer. Sure, it’s not very "useful," but it’s definitely pretty, and you’ll know that you’ll always have one of the defining symbols of modern mathematics right at your fingertips.

And, of course, it’s an awesome way to pick up chicks at the bar or dance club. I mean, come on, flash ’em the old Mandelbrot set, and they’ll be all over you, am I right? Anyone?

Just as a refresher, the Mandelbrot set is plotted by iterating through the complex quadratic polynomial zn+1 = zn2 + c, where c is each “pixel” within the range of the complex plane we want to plot. If the sequence is bounded for a given c (within a certain number of iterations), the point is considered part of the Mandelbrot set, and the pixel is colored black. If the sequence is unbounded for a given c, the color of the pixel is determined by how “fast” the sequence diverges. The more iterations we take for our calculation, the more “precise” the set’s boundary will be.

Here are some fundamental requirements for the application:

• Render the Mandelbrot set using a predefined color palette
• Allow the user to "move" the drawing by pressing the L, R, U, and D keys
• Allow the user to "zoom" in and out of the Set by pressing, say, the 1 and 3 keys
• Allow the user to decrease/increase iterations by pressing, oh I don’t know, the 7 and 9 keys, respectively

### Creating a New Project

Now that we have some requirements, let’s get down to business. We’ll create a brand new project in the Java ME SDK, and we’ll call it something original, like Mandelbrot:

Using all of the defaults for the purposes of this project is just fine. The SDK should generate a project that targets CLDC 1.1 (Connected Limited Device Configuration) and MIDP 2.0 (Mobile Information Device Profile). It will also automatically create a MIDlet class that represents our new application.

The automatically-generated class descends from the base `MIDlet` class, and implements the `CommandListener` interface, which enables our app to "listen" to commands that we can assign to buttons on your phone. The class will be called something like `HelloMIDlet`, but we can easily rename it to something more pertinent like `MandelbrotApp`, and erase the "hello world" code so we have a totally clean class.

Theoretically, however, in addition to a class that extends `MIDlet`, we’ll also need a class that extends the base class `Canvas` (we’ll call it `MandelbrotCanvas`), so that we can perform any kind of graphics operations we need. This class will also be responsible for capturing keystrokes from the phone’s keypad (this is different from capturing "commands" which the `MIDlet` class does).

### The Code

Let’s first go over the `MandelbrotApp` class. Here are the first few lines of the class, followed by some explanation:

In the above code, we perform some initialization of things we’ll use later on. First we create an instance of our canvas object (`MandelbrotCanvas`), and assign two commands ("exit" and "about") to the canvas. This means that when the canvas becomes visible, these two commands will become available from the two top buttons of your handset’s keypad. Also, by setting the canvas’ `CommandListener` to `this`, we’re saying that this class will handle the commands issued while the canvas is displayed. The variables `rangex1`, `rangex2`, `rangey1`, and `rangey2` represent the initial boundaries for our Mandelbrot calculation. By manipulating these variables we can pan and zoom in and out of the image.

We also define a color palette that we’ll use when rendering the Mandelbrot set. The color palette contains 256 entries, and is simply a gradient of colors from red, to green, to blue, and back to red. Additionally, we define a variable called `scanlineBuffer` which will actually contain the screen contents before they’re painted onto the screen. We leave this initialized to `null`, because we’ll dynamically allocate this buffer the first time our `paint` event is called.

Next, we’ll create a function that actually renders the Mandelbrot set onto our screen buffer. This function uses the standard Mandelbrot algorithm without any fancy attempts at optimization, so it may be slower for some phones than others (on some phones it will be god-awful slow; sorry!).

Notice in the above function that, inside the outer loop, we force a repaint of the canvas, so that the user gets a sense of the graphic actually being drawn in real time. If we didn’t do this, the app would be totally unresponsive until all of the image is rendered.

When the app is started, the following function is called, where we set the canvas to be the currently-displayed object, and call the Mandelbrot rendering function:

Another point of interest in this class is the paint handler. This function actually gets called from the Canvas class (see lower), but I put the paint code in this class for convenience.

In the above function, all we do is draw our screen buffer to the screen, then write some text over the image, which includes a little copyright message and the current number of iterations used in the Mandelbrot calculation. Note that we dynamically get the height of the phone’s font (and adjust accordingly), since the font varies greatly between different phone models.

The other interesting function in this class is the command handler. This function will be called when either the "Exit" or "About" commands are pressed while our app is running. If "Exit" is pressed, we’ll destroy the application. If "About" is pressed, we’ll display a simple `Alert` message:

Finally, let’s have a quick look at the `MandelbrotCanvas` class:

The only relevant functions in the above class are the `paint` function, which is called automatically whenever the screen needs repainting, and the `keyPressed` function, which gets called when the user presses any of the keys on the keypad.

Notice how pressing the Up/Down/Left/Right buttons causes the x- and y-ranges to be panned to simulate the effect of scrolling, and the "1" and "3" keys have the effect of zooming. Keys "7" and "9" are also programmed to decrease and increase the number of iterations by 4. After any key is pressed, the graphic is redrawn due to `RenderMandelbrot()` being called again.

### Testing the App

That’s about all there is to it. The next step is to test how the app works. If we run the app from the IDE of the Java ME SDK, it automatically launches a default emulator and loads the app onto it:

Seems to work fine on the emulator! Now how about getting it onto an actual phone? Building the app produces two files: a .JAR file, which is the actual app, and a .JAD file, which is a text file that contains certain descriptions about the app (such as the author, copyright, and URL). But what do we do with these files?

Loading a Java app onto a phone can be done in a few different ways:

• Load from a memory card
• Hack right into the phone

I’m fortunate enough to have a Motorola RAZR V3xx, which has a microSD slot. I was amazed how easy it was to get it up and running on this phone. Here’s all that’s required to install a Java app onto this phone (and probably similar Motorola models that accept a microSD card):

• With the microSD card in the phone, connect a USB cable from your computer to the phone (it will map as a disk drive)
• Copy your app’s .JAR and .JAD files to the `/mobile/kjava` directory
• Disconnect the USB cable from the phone
• On the phone, go to Menu -> My Stuff -> Games & Apps -> [Install New], and select your app from the list
• That’s it! The app will now be installed on the phone!

### Installing over the Web

If you don’t have a phone that lets you install apps from a microSD card, you can download the app from the Web using your phone. This is, of course, only if your phone has an active account and supports Web access. You’ll also probably be paying a few cents for the data transfer, depending on the wireless plan you purchased from your carrier. Oh, and of course, your phone must support CLDC 1.1 (1.0 doesn’t have floating-point support), and MIDP 2.0, which most modern phones do.

Now then, if you want to load an app that you wrote onto your phone over the Web, you need to have access to a web server where you can place your app to be downloaded. For my example, I’ll use my web server, `dmitrybrant.com`, and I’ll put the app in a subdirectory, like so:

I put both the .JAR and .JAD files in the "jme" subdirectory. To download the app, you only need to link to the .JAD file. But wait! There’s one more crucial step to take before our app can be downloaded from a phone. We need to edit the `.htaccess` file in this directory, and add the proper MIME types for our files:

Once this is done, we can try downloading the app to our phone. After a minute of fat-fingering the URL, agreeing to install an unsigned app, and waiting for it to finish installing… lo and behold:

For the record, the above screen took about 20 seconds to draw on my V3xx. Your phone may be significantly slower (or faster, but probably not). So be prepared to wait a bit for the drawing to complete. Or go ahead and optimize the code to use integer-only math! (Let me know if you do!)

Browse the source code for this project on GitHub.

## Seven-Segment Display for .NET

I’m usually not a big fan of custom controls except in the most extreme circumstances. From the point of view of usability, it should always make the most sense to use the controls that are shipped with the Operating System. Your user base is already familiar with the OS’s native controls, so creating custom controls would only add to the learning curve for your application. But I digress. Sometimes, there are certain controls that just beg to be written, whether they’re useful or not.

That’s why I decided to write this seven-segment LED control: not because it’s any more "useful" than a standard Label control, but because it looks freakin’ sweet. I also wrote the control to become more familiar with the internals of C# and .NET in general. And, if you like the control and are able to use it, or learn from it, so much the better.

Even if you haven’t heard the name "seven-segment display" before, you’ve probably seen quite a few in your lifetime. They appear on pretty much every piece of electronic equipment that needs to display numbers for any reason, like the timer on a microwave oven, the display on a CD player, or the time on your digital wristwatch.

They’re called seven-segment displays because they’re actually made up of seven "segments" — seven individual lights (LEDs or otherwise) that light up in different patterns that represent any of the ten digits (0 – 9).

So, what are you waiting for? Download the test application which the screen shot is from. (Or browse the source code on GitHub)

### Using the code

This custom control can be built into your application by simply including the "SevenSegment.cs" file in your project. Rebuild your project, and you’ll be able to select the `SevenSegment` control from your tool palette and drop it right onto your forms.

To replicate the look of a seven-segment display, I draw seven polygons that precisely match the physical layout of a real display. To model the polygons, I drew them out on graph paper, and recorded the coordinates of each point in each polygon. To draw the polygons on the control, I use the `FillPolygon` function, passing it the array of points that represent the polygon. Let’s examine the control’s `Paint` event to see exactly what’s going on:

You can set the value displayed in the control through two properties: `Value` and `CustomPattern`. The `Value` property is a string value that can be set to a single character such as "5" or "A". The character will be automatically translated into the seven-segment bit pattern that looks like the specified character.

If you want to display a custom pattern that may or may not look like any letter or number, you can use the `CustomPattern` property, and set it to any value from 0 to 127, which gives you full control over each segment, since bits 0 to 6 control the state of each of the corresponding segments.

The way it’s done in the code is as follows. I have an enumeration that encodes all the predefined values that represent digits and letters displayable on seven segments:

Notice that each value is a bit map, with each bit corresponding to one of the seven segments. Now, in the `set`ter of the Value property, I compare the given character against our known values, and use the corresponding enumeration as the currently displayed bit pattern:

Either way, the bit pattern to be displayed in the control ends up in the `customPattern` variable, which is then used in the `Paint` event as shown above.

You can also "italicize" the display by manipulating the `ItalicFactor` property. This value is simply a shear factor that gets applied when drawing the control, as seen in the `Paint` event. An italic factor of -0.1 makes the display look just slightly slanted, and a whole lot more professional.

If you begin noticing that the segments are being drawn outside the boundary of the control (perhaps from too much italicizing), you can use the `Padding` property and increase the left/right/top/bottom padding until all of the shapes are within the control’s client rectangle.

The control has several other convenient properties for you to play with, such as the background color, the enabled and disabled color for the segments, and the thickness of the segments.

### Seven-segment array

In addition to the seven-segment control itself, I’m throwing in another control which is an array of seven-segment displays. This allows you to display entire strings on an array of 7-seg displays. Check out the demo application, and dig around the source code to see how it’s used; it’s really simple.

To use the array control, include the "SevenSegmentArray.cs" file in your project and rebuild. You’ll then be able to select the `SevenSegmentArray` control from the tool palette.

This control has an `ArrayCount` property that specifies the number of 7-seg displays in the array, as well as a `Value` property that takes any `string` to be displayed on the array. Easy, right?

### Other thoughts

I must say I had a lot of fun writing this control, and .NET helped put a lot of the fun into it by making it incredibly easy to draw your own shapes, transform coordinates, and introduce truly powerful properties.

Also, coming from somewhat of an electronics background, for me, seeing this control brings a certain nostalgia for simpler times. I hope you enjoy it.