Skip to content

Tag: Java

Arduino and Java

Arduino

Arduino is a free popular platform for embedded programming based on a simple I/O board easily programmable. Interfacing it with Java allow us to create sophisticated interfaces and take advantages from the several API available in the Java ecosystem.

I’m following the original Arduino and Java interfacing tutorial by Dave Brink but in a more practical approach and with more details.

Step 1) Install the Arduino IDE

This is not a completely mandatory step but it will easy a lot our work. Our program will borrow some Arduino IDE libraries and configurations  like which serial port it is using and at which boud rate. At the moment I wrote this tutorial the version of Arduino IDE was 0013.

Step 2) Prepare your Arduino

Connect your Arduino to the serial port in your computer. Here I’m connecting my Arduino with my laptop throught a USB.

Arduino

Make sure your Arduino IDE is configured and communicating well if your Arduino. Let put on it a little program that sends to us a mensage:

void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.println("Is there anybody out there?");
  delay(1000);
}

Step 3) Install RXTX Library

We will use some libraries to acess the serial port, some of them relies on binary implementations on our system. Our first step is to install the RXTX library (Java CommAPI) in your system. In a Debian like Linux you can do that by:

sudo apt-get install librxtx-java

Or using a graphical package tool like Synaptic:

installing rxtx

For others systems like Windows see the RXTX installation docs.

Step 4) Start a new NetBeans project

Again, this is not a mandatory step but will easy a lot our work. NetBeans is a free and open source Java IDE that will help us to develop our little application. Create a new project at File → New Project and choose at Java at Categories and Java Application at Projects.

netbeans new project

Chose a name for your project. I called mine SerialTalker.

name your project

At the moment I wrote this tutorial I was using Netbeans version 6.5 and Java 6 update 10 but should work as well on newer and some older versions

Step 5) Adding Libraries and a Working Directory

On NetBeans the Projects tab, right-click your project and choose Properties.

libraries

On the Project Properties window select the Libraries on the Categories panel.

Netbeans project libraries

Click the Add JAR/Folder button.

arduino directory

Find where you placed your Arduino IDE installation. Inside this directory there’s a lib directory will some JAR files. Select all them and click Ok.

jars libraries

As we want to borrow the Arduino IDE configuration the program needs to know where is they configuration files.  There’s a simple way to do that.

Still in the Project Properties window select Run at Categories panel. At Working Directory click in the Browse button and select the directory of your Arduino IDE. Mine is at /home/silveira/arduino-0013.

Working directory

You can close now the Project Properties window. At this moment in autocomplete for these libraries are enable in your code.

netbeans autocomplete

Step 6) Codding and running

Here is the code you can replace at Main.java in your project:

package serialtalk;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.InputStream;
import java.io.OutputStream;
import processing.app.Preferences;

public class Main {
    static InputStream input;
    static OutputStream output;

    public static void main(String[] args) throws Exception{
        Preferences.init();
        System.out.println("Using port: " + Preferences.get("serial.port"));
        CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(
                Preferences.get("serial.port"));

        SerialPort port = (SerialPort)portId.open("serial talk", 4000);
        input = port.getInputStream();
        output = port.getOutputStream();
        port.setSerialPortParams(Preferences.getInteger("serial.debug_rate"),
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
        while(true){
            while(input.available()>0) {
                System.out.print((char)(input.read()));
            }
        }
    }
}

Now just compile and run (with your Arduino attached in your serial port and running the program of step 2).

voillá

There is. Now you can make your Java programs to talk with your Arduino using a IDE like NetBeans to create rich interfaces.

Game map edition using Tiled

Tiled logo

Tiled is general purpose game map editor, with support of several map formats (XML, JSON), multi plataform and runs installed or from browser, supports plugins to read and write others map formats and all free (under GPL license).

map editor tiles tileset game deveopment

Installing

You can lauch Tiled via Java Web Start or download it’s lastest version zip file. After download it just unzip it and run:

java -jar tiled.jar

Make sure you have at least Java 1.5 installed and configured.

Creating a empty map

After lauching it, open the menu File → New and create a new 10×10 orthogonal map with 32×32 tiles.

Tiled: New Map

Like this one

tiled 10x10 map

Creating a tileset

Now we need to add a tileset to start drawing a map. Let’s use this one

batalhao tileset cc by sa

Save the tileset image above.  Open the menu Tilesets → New Tileset select Reference tileset image and browser to find the tileset image you saved. Keep tile width and height as 32 and tile spacing and margin as 0.

tiled new tileset

Notice a new tab on the Tile palette section.

tiled tileset

Working with layers

Select the first grass tile from the tileset and select the  fill tool (bucket icon) to create a grass field. Use the paint tool (pencil icon) to add some stones and trees at random locations on grass. On the Layers section double click at Layer Name and put a name like “field”.

tiled field

Now let’s create another layer to put the buildings and streets. We can do that by opening the menu Layer → Add Layer or just clicking the new icon on layer’s section. Let’s call it “city”.

Now build your city by selecting tiles on the palette and using the paint tool. There’s tiles for horizontal and vertical street and all kinds of intersection. For the building you can click and drag in the palette to select multiple tiles at once.

tiled city

Saving

You can save the map as tmx (XML Tiled map file) , JSON, LUA, wlk, map (Mappy) or export it as a image. There’s some options accessible on the Edit → Preferences menu like use base-64  gziped encoding.

Thanks to Adam Turk and Bjørn Lindeijer for developing that great project.

In a next post I want to show how to integrate this with a Java/JavaFX game.

Slides Resumos para a SCJP

O João Sávio, Embaixador de Campus da Sun na Unesp Rio Claro preparou vários resumos em slides para quem está estudando para a certificação SCJP. Eles me pareceram muito bons para quem já leu e já aprendeu o básico sobre o assunto e agora está busacando um material de fixação.

Aqui está um deles, o de Conjuntos e Tipos Genéricos:

O restante dos resumos você confere nesse post no blog do João Sávio.

Gravatar with JavaFX

Gravatar is easy way to put global recognized avatar images into any Internet application. Gravatar would stands for globally recognized avatar.

Below,  the Java class that I got from the Gravatar Java reference. Here is a static class called md5 that applies a MD5Sum algorithm over a string. Is a little complex code but all behavior keeps encapsulated and who uses it don’t need to know how it works. Just gives a string and receives a encrypted string. Those two codes are also a good example of how calling Java classes inside a JavaFX code.

package gravatarexample;

import java.security.MessageDigest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

public class MD5 {
   public static String toHex(String message) {
      try {
         MessageDigest md = MessageDigest.getInstance("MD5");
         byte array[] = md.digest(message.getBytes("CP1252"));
         StringBuffer sb = new StringBuffer();
         for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i]&0xFF)|0x100).substring(1, 3));
         }
         return sb.toString();
      } catch (NoSuchAlgorithmException e) {
      } catch (UnsupportedEncodingException e) {
      }
      return null;
   }
}

As a Java class in the same package, any JavaFX (or Java) code can call it without any problem. Just to keep the code more clear I’m importing it explicitly. Is this example I also create some Swing interface to give user the option to put his mail, adjust the image size and get a output direct link or html image tag.

package gravatarexample;

import gravatarexample.MD5;
import javafx.ext.swing.SwingButton;
import javafx.ext.swing.SwingSlider;
import javafx.ext.swing.SwingTextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.Scene;
import javafx.stage.Stage;

var mail = "Email";
var key = "";

function gravatalize(mail:String, size: Integer): String {
   return "http://www.gravatar.com/avatar/{MD5.toHex(mail)}?s={size}"
}

var inputtxt = SwingTextField {
   columns: 20
   text: mail
}

var slider = SwingSlider {
   minimum: 10
   maximum: 128
   value: 100
   vertical: false
}

var button = SwingButton {
   text: "Get Gravatar"
   action: function() {
      key = gravatalize(inputtxt.text, slider.value);
      directoutput.text = key;
      htmloutput.text = "\"gravatar\"";
      photo.image = Image {
         backgroundLoading: true,
         url: key};
   }
}

var photo:ImageView = ImageView {
   image: null
}

var directoutput = SwingTextField {
   columns: 20
   text: "direct link image"

}

var htmloutput = SwingTextField {
   columns: 20
   text: "html tag image"
}

Stage {
   title: "Gravatar"
   width: 300
   height: 340
   scene: Scene {
      content: [
         VBox {
            spacing: 10
            content: [inputtxt, slider, button, directoutput, htmloutput, photo]
         },
      ]
   }
}

The string itself is assembled in the gravatalize function. You give a mail and it’s returns a Gravatar direct link to the image. There’s many cool ways to use together Gravatar and a JavaFX Internet application.

JavaFX, how to create a rpg like game

JavaFX 1.0 is out and there are tons of new cool features, specially for game development.trans

I’ll show in this tutorial how to create a very simple demo that shows how to load imtrages, handle sprites, collisions and keyboard events that you can use to create a game with a old school rpg like vision.

For the background scenario I’m using the house that I drew and we’ll call as house.png.

That we load as a Image and place into a ImageView.

ImageView{
   image: Image {url: "{__DIR__}house.png"}
}

For the character I’m using the last character I drew, the nerdy guy.

To make the animation easier, I spited it into 9 pieces:

down0.png, down1.png and down2.png

left0.png, left1.png and left2.png

right0.png, right1.png and righ2.png

up0.png, up1.png and up2.png

All images I’m using should be in the same directory of source code.

Let’s start loading the scenario and a single character sprite.

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.*;

Stage {
   title: "RPG-like demo", width: 424, height: 412
   visible: true
   scene: Scene{
      content: [
         ImageView{
         image: Image {url: "{__DIR__}house.png"} },
         ImageView{
            x: 320 y: 80
            image: Image {url: "{__DIR__}down1.png"}
         }
      ]
   }
}

Saved as Game.fx you can compile and run with in your terminal:

$ javafxc Game.fx

$ javafx Game

Hint: You can use NetBeans 6.5 JavaFX plugin to easier the JavaFX development.

To put animation on the character we load all sprites into four lists. Each list for each direction.

// sprites
def up    = for(i in [0..2]) { Image {url: "{__DIR__}up{i}.png"    } }
def right = for(i in [0..2]) { Image {url: "{__DIR__}right{i}.png" } }
def down  = for(i in [0..2]) { Image {url: "{__DIR__}down{i}.png"  } }
def left  = for(i in [0..2]) { Image {url: "{__DIR__}left{i}.png"  } }

And create vars to store the character position and frame of animation.

var frame = 0;
var posx = 320;
var posy = 80;

Also store the house background.

// house background
def house = ImageView{ image: Image {url: "{__DIR__}house.png"} };

I create booleans to store some key states and at each interval of time I see how they are and do something about. You can handle keyboard event with less code but I like this way because keep visual and game logics a little bit more separated.

// keyboard
var    upkey = false;
var rightkey = false;
var  downkey = false;
var  leftkey = false;

// player
var player = ImageView{
   x: bind posx y: bind posy
   image: Image {url: "{__DIR__}down1.png"}
   onKeyPressed: function(e:KeyEvent){
      if (e.code == KeyCode.VK_DOWN) {
      downkey = true;
      } else if (e.code == KeyCode.VK_UP) {
         upkey = true;
      }else if (e.code == KeyCode.VK_LEFT) {
         leftkey = true;
      }else if (e.code == KeyCode.VK_RIGHT) {
         rightkey = true;
      }
   } // onKeyPressed

   onKeyReleased: function(e: KeyEvent){
      if (e.code == KeyCode.VK_DOWN) {
         downkey = false;
      } else if (e.code == KeyCode.VK_UP) {
         upkey = false;
      }else if (e.code == KeyCode.VK_LEFT) {
         leftkey = false;
      }else if (e.code == KeyCode.VK_RIGHT) {
         rightkey = false;
      }
   } // onKeyReleased
}

See a video of the game working so far:

[youtube]Xv5z-9LGuOc[/youtube]

Now we will add collisions. In a previous post I showed some math behind bounding box game collisions. The good news are that you no longer need to worry about that. There are a lot of API improvements in JavaFX 1.0 that do all the hard work for you, specially the new classes on javafx.geometry package, Rectangle2D and Point2D.

We create rectangles that represent the obstacles in the house.

// collidable obstacles
def obstacles = [
	Rectangle { x:   0 y:   0 width:  32 height: 382 stroke: Color.RED },
	Rectangle { x:   0 y:   0 width: 414 height:  64 stroke: Color.RED },
	Rectangle { x: 384 y:   0 width:  32 height: 382 stroke: Color.RED },
	Rectangle { x:   0 y: 192 width: 128 height:  64 stroke: Color.RED },
	Rectangle { x: 192 y: 192 width:  64 height:  64 stroke: Color.RED },
	Rectangle { x: 224 y:   0 width:  32 height: 288 stroke: Color.RED },
	Rectangle { x: 288 y: 128 width:  96 height:  64 stroke: Color.RED },
	Rectangle { x:   0 y: 352 width: 128 height:  32 stroke: Color.RED },
	Rectangle { x: 192 y: 352 width: 192 height:  32 stroke: Color.RED },
	Rectangle { x: 224 y: 320 width:  32 height:  32 stroke: Color.RED },
	Rectangle { x:  32 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  96 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 128 y:  64 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 192 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y: 128 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  32 y: 250 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y: 250 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 200 y: 255 width: 20 height: 20 stroke: Color.YELLOW },
	Rectangle { x: 200 y: 170 width: 20 height: 20 stroke: Color.YELLOW },
	Rectangle { x: 257 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 288 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 320 y: 192 width: 64 height: 64 stroke: Color.YELLOW },
	Rectangle { x: 352 y: 295 width: 32 height: 60 stroke: Color.YELLOW },
	Rectangle { x:  32 y: 327 width: 64 height: 23 stroke: Color.YELLOW },
];

We just have to change a little bit the game logics in order to handle collisions.

We define a bounding box around the player, it’s a rectangle from (4, 25) at the player coordinates system and with width 19 and height 10. The idea is to prospect where the player will be in the next step, see if it’s bouding box don’t collide with any obstacle and so pass it to the real game position.

// game logics
var gamelogics = Timeline {
   repeatCount: Timeline.INDEFINITE
   keyFrames: KeyFrame {
      time : 1s/8
      action: function() {
         var nextposx = posx;
         var nextposy = posy;
         if(downkey) {
            nextposy += 5;
            player.image = down[++frame mod 3];
         }
         if(upkey) {
            nextposy -= 5;
            player.image = up[++frame mod 3];
         }
         if(rightkey) {
            nextposx += 5;
            player.image = right[++frame mod 3];
         }
         if(leftkey) {
            nextposx -= 5;
            player.image = left[++frame mod 3];
         }
         for(obst in obstacles) {
            if(obst.boundsInLocal.intersects(nextposx + 4, nextposy + 25, 19, 10)) {
               return;
            }
         }
         posx = nextposx;
         posy = nextposy;
      }
   }
}

This is enough to do the trick but I also added a way to smoothly show the obstacles when pressing the space key.

[youtube]k-MHh6irvwE[/youtube]

Here is the complete source code.

package Game; 

import javafx.stage.Stage;
import javafx.scene.*;
import javafx.scene.image.*;
import javafx.scene.input.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.animation.*;

var frame = 0;
var posx = 320;
var posy = 80;

// sprites
def up    = for(i in [0..2]) { Image {url: "{__DIR__}up{i}.png"    } }
def right = for(i in [0..2]) { Image {url: "{__DIR__}right{i}.png" } }
def down  = for(i in [0..2]) { Image {url: "{__DIR__}down{i}.png"  } }
def left  = for(i in [0..2]) { Image {url: "{__DIR__}left{i}.png"  } }

// house background
def house = ImageView{ image: Image {url: "{__DIR__}house.png"} };

// keyboard
var    upkey = false;
var rightkey = false;
var  downkey = false;
var  leftkey = false;

// player
var player = ImageView{
   x: bind posx y: bind posy image: down[1]
   onKeyPressed: function(e:KeyEvent){
      if (e.code == KeyCode.VK_DOWN) {
         downkey = true;
      } else if (e.code == KeyCode.VK_UP) {
         upkey = true;
      }else if (e.code == KeyCode.VK_LEFT) {
         leftkey = true;
      }else if (e.code == KeyCode.VK_RIGHT) {
         rightkey = true;
      }

		if(e.code == KeyCode.VK_SPACE){
         if(fade==0.0){
         	fadein.playFromStart();
			}
			if(fade==1.0){
				fadeout.playFromStart();
			}
		}
   } // onKeyPressed

   onKeyReleased: function(e: KeyEvent){
      if (e.code == KeyCode.VK_DOWN) {
         downkey = false;
      } else if (e.code == KeyCode.VK_UP) {
         upkey = false;
      }else if (e.code == KeyCode.VK_LEFT) {
         leftkey = false;
      }else if (e.code == KeyCode.VK_RIGHT) {
         rightkey = false;
      }
   } // onKeyReleased
}

// collidable obstacles
def obstacles = [
	Rectangle { x:   0 y:   0 width:  32 height: 382 stroke: Color.RED },
	Rectangle { x:   0 y:   0 width: 414 height:  64 stroke: Color.RED },
	Rectangle { x: 384 y:   0 width:  32 height: 382 stroke: Color.RED },
	Rectangle { x:   0 y: 192 width: 128 height:  64 stroke: Color.RED },
	Rectangle { x: 192 y: 192 width:  64 height:  64 stroke: Color.RED },
	Rectangle { x: 224 y:   0 width:  32 height: 288 stroke: Color.RED },
	Rectangle { x: 288 y: 128 width:  96 height:  64 stroke: Color.RED },
	Rectangle { x:   0 y: 352 width: 128 height:  32 stroke: Color.RED },
	Rectangle { x: 192 y: 352 width: 192 height:  32 stroke: Color.RED },
	Rectangle { x: 224 y: 320 width:  32 height:  32 stroke: Color.RED },
	Rectangle { x:  32 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  96 y:  64 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 128 y:  64 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 192 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y: 128 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  32 y: 250 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x:  64 y: 250 width: 64 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 200 y: 255 width: 20 height: 20 stroke: Color.YELLOW },
	Rectangle { x: 200 y: 170 width: 20 height: 20 stroke: Color.YELLOW },
	Rectangle { x: 257 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 288 y:  32 width: 32 height: 32 stroke: Color.YELLOW },
	Rectangle { x: 320 y: 192 width: 64 height: 64 stroke: Color.YELLOW },
	Rectangle { x: 352 y: 295 width: 32 height: 60 stroke: Color.YELLOW },
	Rectangle { x:  32 y: 327 width: 64 height: 23 stroke: Color.YELLOW },
];

// game logics
var gamelogics = Timeline {
   repeatCount: Timeline.INDEFINITE
   keyFrames: KeyFrame {
      time : 1s/8
      action: function() {
         var nextposx = posx;
         var nextposy = posy;
         if(downkey) {
            nextposy += 5;
            player.image = down[++frame mod 3];
         }
         if(upkey) {
            nextposy -= 5;
            player.image = up[++frame mod 3];
         }
         if(rightkey) {
            nextposx += 5;
            player.image = right[++frame mod 3];
         }
         if(leftkey) {
            nextposx -= 5;
            player.image = left[++frame mod 3];
         }
         for(obst in obstacles) {
            if(obst.boundsInLocal.intersects(nextposx + 4, nextposy + 25, 19, 10)) {
               return;
            }
         }
         posx = nextposx;
         posy = nextposy;
      }
   }
}

gamelogics.play();

// obstacles view
var fade = 0.0;

var obstacleslayer = Group {
   opacity: bind fade
   content: [
      Rectangle { x:0 y:0 width:500 height: 500 fill: Color.BLACK },
      obstacles,
      Rectangle {
        x: bind posx + 4 y: bind posy + 25 width: 19 height: 10
        fill: Color.LIME
      }
   ]
}

var fadein = Timeline {
	keyFrames: [
   	at (0s) {fade => 0.0}
   	at (1s) {fade => 1.0}
   ]
}

var fadeout = Timeline {
	keyFrames: [
   	at (0s) {fade => 1.0}
   	at (1s) {fade => 0.0}
   ]
}

// game stage
Stage {
	title: "RPG-like demo", width: 424, height: 412
	visible: true
	scene: Scene{
      fill: Color.BLACK
		content: [house, player, obstacleslayer]
	}
}

Play Through Java Web Start

or click here to play via applet, inside your browser.

update: The applet version and Java Web Start versions should be working now.  The applet version on Linux seems to be having problems with the keyboard handling, use the Java Web Start version while I’m trying to fix it.

Downloads:

Buzz on JavaFX and Inkscape


At November, 26, on the main page of java.sun.com at the section From The Blogosfere

Thanks for all comments, suggestions and feedback on the post Inkscape and JavaFX working together. The JavaFX guru James Weaver posted about on his blog and it also figured out on java.sun.com on the From The Blogosfere section.

Bob said that there are build binaries of Inkscape for Windows, so we can already see it 0.46-devel working without compiling yourself yours.

\o/

And hey, Project Xort won a second place prize at the MySQL and GlassFish Student Reviews Contest. A lot of guys here from Brazil were prized, congractulations guys!

JavaFX, Defuse the Bomb

I continue to develop simple games demos to feel better the strengths and weakness of JavaFX for game development.

Preview:

[youtube]hR2LiKiBUgE[/youtube]

Click to play via Java Web Start:

There’s a little JavaFX game demo where you have to transport a bomb to a defuse point without touching in the walls. I’m using the collision detection methods I described early in this post to detect when the bomb hits a wall and then explode or when a bomb is inside the defuse point and the game ends. As it’s only a demo, it’s just one single level, but adding more levels would be easy.

Basically we have this four images:


bomb.png


goal.png


floor.png


wall.png

The code is petty simple. A little bit more than 300 lines with even with all comments and declarations. I transform the bomb image into a draggable node, create a list of collidable nodes and a especial node, the goal. I check the collisions when the bomb is dragged by mouse, if it hits something, it blows up.

I use extensively the TimeLine class from the animation framework (javafx.animation) to create chained animations and even to control some game logic.

As I focused in the simplicity, I don’t declared any classes to after instantiate their objects. I just was using common classes from JavaFX and putting logic on ir throught event and binding to external variables.

import javafx.application.Frame;
import javafx.application.Stage;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.animation.Interpolator;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.geometry.Circle;
import javafx.scene.geometry.Rectangle;
import javafx.scene.geometry.Shape;
import javafx.scene.text.Text;
import javafx.scene.Font;
import javafx.scene.FontStyle;
import javafx.input.MouseEvent;

/* Fade variable modified in some animations and used in the fadescreen */
var fade = 0.0;

/* The Bomb */
var lock = false;
var tx = 0.0;
var ty = 0.0;
var bomb:Node = Group{
    opacity: bind bombfade;
    content: [
        ImageView {
            image: Image {
                url: "{__DIR__}/bomb.png"
            }
        },
        Circle {
            centerX: 45, centerY: 21, radius: 7, fill: Color.LIME
            opacity: bind led
        },
        Circle {
            centerX: 30, centerY: 30, fill: Color.WHITE
            radius: bind fireradius
        },
    ],
    var startX = 0.0;
    var startY = 0.0;
    translateX: bind tx
    translateY: bind ty

    onMousePressed: function( e: MouseEvent ):Void {
        if (lock) {return;}
        startX = e.getDragX() - tx;
        startY = e.getDragY() - ty;
    }

    onMouseDragged: function(e:MouseEvent):Void {
        if (lock) {return;}
        tx = e.getDragX() - startX;
        ty = e.getDragY() - startY;
        checkcollissions();
    }
}

/* Big rectangle that covers all the screen (bomb explosion or game end) */
var fadescreen = Rectangle {
    x: 0, y: 0, width: 640, height: 480, fill: Color.WHITE
    opacity: bind fade
}

/* The wood floor image for the scenario. */
var floor = ImageView {
    image: Image {
        url: "{__DIR__}/floor.png"
    }
}

/* The goal image where the bomb should be placed. */
var goal = ImageView {
    x: 470, y: 360
    image: Image {
        url: "{__DIR__}/goal.png"
    }
}

/* List of obstacles nodes that the bomb can collide with. */
var obstacles = [
    Rectangle { x: 120, y: 0, width: 100, height: 300, fill: Color.BLACK},
    Rectangle { x: 350, y: 200, width: 100, height: 300, fill: Color.BLACK},
    Rectangle { x: 370, y: 50, width: 50, height: 50, fill: Color.BLACK},
    Rectangle {
        x: 250, y: 120, translateX: bind move, width: 100, height: 50
        fill: Color.BLACK
    },
];

/* Visible representations of obstacles */
var wallimage = Image {
    url: "{__DIR__}/wall.png"
}
var walls = for(obs in obstacles){
    ImageView {
        x: obs.x, y: obs.y, translateX: bind obs.translateX
        clip: obs, image: wallimage
    }
}

/* Animation for a blinking green led */
var led = 0.0;
var bombclock = Timeline {
    repeatCount: Timeline.INDEFINITE
    autoReverse: true
    keyFrames : [
        KeyFrame {
            time : 0s
            values : led => 0.0 tween Interpolator.LINEAR
        },
        KeyFrame {
            time : 1s
            values : led => 1.0 tween Interpolator.LINEAR
        }
    ]
}

/* Animation for the bomb explosion and game reset */
var fireradius = 0.0;
var explosion:Timeline = Timeline {
    repeatCount: 1
    keyFrames : [
        KeyFrame {
            time : 0s
            values : [
                fireradius => 0.0,
                fade => 0.0
            ]
        },
        KeyFrame {
            time : 2s
            values : [
                fireradius => 200.0 tween Interpolator.LINEAR,
                fade => 1.0 tween Interpolator.LINEAR
            ]
            action: gamereset
        },
        KeyFrame {
            time : 3s
            values: fade => 0.0 tween Interpolator.LINEAR
        },
    ]
}

/* Reset variables for initial values */
function gamereset(){
    lock = false;
    fireradius = 0.0;
    tx = 0.0;
    ty = 0.0;
    bombfade = 1.0;

    moveblock.start();
    specialcollison.start();
    bombclock.start();
}

/* Animation when the bomb reaches the goal. Bomb disapear. */
var bombfade = 1.0;
var bomdisapear = Timeline {
    repeatCount: 1
    keyFrames : [
        KeyFrame {
            time : 1s
            values: [
                        bombfade => 0.0 tween Interpolator.EASEBOTH,
                        fade => 0.0
            ]
        },
        KeyFrame {
            time : 2s
            values:
                    fade => 1.0 tween Interpolator.LINEAR;
            action: gamereset
        },
        KeyFrame {
            time : 3s
            values:
                    fade => 0.0 tween Interpolator.LINEAR;
        },
    ]
}

/* Animation for a moving block. */
var move = 0.0;
var moveblock = Timeline {
    repeatCount: Timeline.INDEFINITE
    autoReverse: true
    keyFrames : [
        KeyFrame {
            time : 0s
            values :
                    move => 0.0
        },
        KeyFrame {
            time : 3s
            values :
                    move => 200.0 tween Interpolator.EASEBOTH
        },
    ]
}

/* Check and handle possible collisions. */
function checkcollissions(): Void {
    if(checkobstacles()){
        lock = true;
        specialcollison.stop();
        moveblock.stop();
        explosion.start();
    }

    if (insidenode(bomb,goal)) {
        lock = true;
        moveblock.stop();
        bomdisapear.start();
    }
}

/* There was a bug, when the bomb is stopped, not been gragged, in front of
the moving block, it could pass through it because checkcollissions() was
only called on mouse moving. This make sure checking this special case. */
var specialcollison:Timeline = Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 1s/5
            action: function(){
                if(hitnode(obstacles[sizeof obstacles-1], bomb)){
                    lock = true;
                    moveblock.stop();
                    explosion.start();
                    specialcollison.stop();
                }
            }
        }
    ]
}

/*
* The next four functions are for collision detection.
* @See http://silveiraneto.net/2008/10/30/javafx-rectangular-collision-detection/
*/

/*
 * Check collision between two rectangles.
 */
function collission(ax, ay, bx, by, cx, cy, dx, dy): Boolean {
    return not ((ax > dx)or(bx < cx)or(ay > dy)or(by < cy));
}

/*
 * Check if the first rectangle are inside the second.
 */
function inside (ax, ay, bx, by, cx, cy, dx, dy):Boolean{
    return ((ax > cx) and (bx < dx) and (ay > cy) and (by < dy));
}

function hitnode(a: Node, b:Node): Boolean {
    return (collission(
        a.getBoundsX(), a.getBoundsY(),
        a.getBoundsX() + a.getWidth(), a.getBoundsY() + a.getHeight(),
        b.getBoundsX(), b.getBoundsY(),
        b.getBoundsX() + b.getWidth(), b.getBoundsY() + b.getHeight()
    ));
}

function insidenode(a:Node,b:Node):Boolean {
    return (inside(
        a.getBoundsX(), a.getBoundsY(),
        a.getBoundsX() + a.getWidth(), a.getBoundsY() + a.getHeight(),
        b.getBoundsX(), b.getBoundsY(),
        b.getBoundsX() + b.getWidth(), b.getBoundsY() + b.getHeight()
    ));
}

/*
* Check collision of bomb against each obstacle.
*/
function checkobstacles(): Boolean{
    for(obst in obstacles){
        if (hitnode(obst, bomb)){
            return true;
        }
    }
    return false;
}

/* Pack visual game elements in a Frame's Stage, unresizable. */
Frame {
    title: "Defuse the Bomb"
    width: 640
    height: 480
    resizable: false
    closeAction: function() {
        java.lang.System.exit( 0 );
    }
    visible: true

    stage: Stage {
        content: bind [floor, goal, walls, bomb, fadescreen]
    }
}

/* Call gamereset to set initial values and start animations */
gamereset();

Downloads:

Apache and JNLP files

To Apache Web Server correctly handles yours JNLP (Java Network Launch Protocol) files, modify or create a .htaccess file in the top directory of your web site and add the following:

AddType application/x-java-jnlp-file    .jnlp
AddType application/x-java-archive-diff .jardiff

Without these MIME-types, the user would see the xml jnlp file as a plain text in the browser. After that you can link to yours Java Web Start applications with a icon like this one:

SCSNI Study Guide

This is a draft of study guide based on SCSNI (Sun Certified Specialist Netbeans IDE) exam objectives.

SCSNI Study Guide
Exam Objetive Resources
Section 1: IDE Configuration
1.1 Demonstrate the ability to configure the functionality available in the IDE, including using enabling and disabling functionality and using the Plugin Manager.
1.2 Explain the purpose of the user directory and the netbeans.conf file and how these can be used to configure the IDE.
1.3 Demonstrate the ability to work with servers in the IDE, such as registering new server instances and stopping and starting servers.
1.4 Describe how to integrate external libraries in the IDE and use them in coding and debugging your project.
1.5 Demonstrate knowledge of working with databases in the IDE, including registering new database connections and tables running SQL scripts.
1.6 Describe how to integrate and use different versions of the JDK in the IDE for coding, debugging, and viewing Javadoc documentation.
Section 2: Project Setup
2.1 Describe the characteristics and uses of a free-form project.
2.2 Demonstrate the ability to work with version control systems and the IDE. (Which VCS’s are available, which ones you need an external client for, how to pull sources out of a repository, view changes, and check them back in).
2.3 Describe the ways in which you can change the build process for a standard project, such as configuring project properties and modifying the project’s Ant build script.
2.4 Configure your project to compile against and run on a specific version of the JDK.
Section 3: Java SE Development
3.1 Demonstrate the ability to create NetBeans projects from the source code of an existing Java SE program.
3.2 Describe how to manage the classpath of a Java SE project, including maintaining a separate classpath for compiling and debugging.
3.3 Demonstrate the knowledge of the NetBeans GUI Builder and the ability to lay out and hook up basic forms using it.
3.4 Demonstrate the ability to package and distribute a built Java Desktop project for use by another user.
Section 4: Java EE Web Development
4.1 Describe how to create a NetBeans project from the source code of an existing Web application.
4.2 Distinguish between a visual web application and web application.
4.3 Demonstrate knowledge of which web frameworks are available in NetBeans IDE and how they are added to and used in a web application.
4.4 Describe how to monitor HTTP requests when running a web application.
4.5 Demonstrate a knowledge of basic tasks related to building and deploying web applications to a server, such as changing the target server and undeploying an application.
Section 5: Editing
5.1 Describe the purpose and uses of refactoring and demonstrate the ability to perform basic refactoring on Java source code.
5.2 Describe how to use the Options window to change the default appearance and behavior of the Source Editor.
5.3 Describe the ways that the IDE highlights errors in source code and the tools the IDE offers for correcting those errors.
5.4 Demonstrate the ability to use editor hints, such as implementing all the methods for an implemented interface
5.5 Demonstrate the ability to use live code templates such as automatic generation of constructors, try/catch loops, and getters and setters.
Section 6: Testing, Profiling, and Debugging
6.1 Demonstrate the ability to work with JUnit tests in the IDE, such as creating JUnit tests and interpreting JUnit test output.
6.2 Describe how to debug a local (desktop) application, including setting breakpoints and stepping through code.
6.3 Describe the difference between local and remote debugging and describe how to debug a remote (web) application.
6.4 Describe the purpose of profiling applications and how to profile a local desktop application in the IDE.

More useful resources:

Please, collaborate in the comments with others resource links (with section number). Let’s complete this guide.