This application displays "Hello World!" in the center of the screen, as well as an Exit button, which terminates the application when pressed. The HelloWorld.java file starts with the following lines of code to import the classes that will be used later in the HelloWorld
class:
import com.sun.kjava.Button;
import com.sun.kjava.Graphics;
import com.sun.kjava.Spotlet;
The following line of code defines our HelloWorld
class as extending Spotlet
:
public class HelloWorld extends Spotlet
Remember that the Spotlet
class provides callbacks for handling events. In this simple example, we're only interested in one event -- when the user taps the Exit button. The next line of code stores a reference to the Exit button:
private static Button exitButton;
As in J2SE, the main()
method defines the main entry point for the program. For a J2ME application, main
also defines the entry point. In this case, the main()
method creates a new instance of the HelloWorld
class, which runs our application.
public static void main(String[] args)
{
(new HelloWorld()).register(NO_EVENT_OPTIONS);
}
The next block of code defines the constructor. Within the constructor, we first create a new Button
and give it the label "Exit." This button initially is invisible. We then get a reference to the graphics object, which is the drawable screen, clear the screen, then draw the text "Hello World!" in the center. Finally, we add the Exit button to the screen.
public HelloWorld()
{
// Create (initially invisible) the "Exit" button
exitButton = new Button("Exit",70,145);
// Get a reference to the graphics object;
// i.e. the drawable screen
Graphics g = Graphics.getGraphics();
g.clearScreen();
// Draw the text, "Hello World!" somewhere near the center
g.drawString("Hello World!", 55, 45, g.PLAIN);
// Draw the "Exit" button
exitButton.paint();
}
Finally, we define the penDown
event handler, which simply checks to see if the Exit button was pressed, and if so, exits the application.
public void penDown(int x, int y)
{
// If the "Exit" button was pressed, end this application
if (exitButton.pressed(x,y))
System.exit(0);
}