Writing and Running your first leJOS NXJ program
The HelloWorld program
Let us start with a simple “Hello World” program. We will create a HelloWorld class in the default java package:
leJOS requires the standard main method for the program entry point:
leJOS NXJ supports the standard java System.out.println method and scroll the output on the NXT LCD screen.
If you run this program as it is, it will display Hello World” and then immediately return to the menu, so you will not be able to see what is displayed (unless you are very quick).
We either need the program to sleep for a while to allow the text to be read, or to wait for a button to be pressed. Let us wait for a button to be pressed. In order to do this, we can call the waitForAnyPress() method of the Button class which is provided by leJOS. But first, we need to import the leJOS NXJ Button class in the program. Button is in the lejos.nxt package, so its full name is lejos.nxt.Button. You can find out what methods a class supports by looking at the API documentation.
The API documentation is on the leJOS web site here and included in the leJOS download in the docs/nxt subfolder.
The complete HelloWorld program is:
Compiling and linking the program
Create a file called
This will the file called HelloWorld.class, which contains the result of the compilation of HelloWorld.java. Unlike a real Java virtual machine, the leJOS firmware does not execute *.class files directly. The HelloWorld program needs to be linked, using the leJOS linker. This is done with the following command:
This will load the class HelloWorld (from HelloWorld.class) and all dependencies. The classes are then merged together into a single file, namely HelloWorld.nxj. However, before that file can be executed, it needs to be uploaded to the NXT brick.
Uploading and running the program
Using the commands above, you obtain the HelloWorld.nxj file. You can now upload it to the NXT brick to execute it. To do that, use the following command:
Also, there is the possibility of the linking a program and uploading the result with one single command. The following command has the same effect as the nxjlink and nxjupload commands above:
The command first creates HelloWorld.nxj and then uploads it to the NXT brick.
The program is automatically started, since the