How to bind data to JavaFX Form

SimpleFormFx.java

/*
 * File: SimpleFormFx.java
 *    Create a SimpleForm from a query
 * Author: https://henry416.wordpress.com/
 *
 * Compile: javac -cp "C:\Program Files\Oracle\JavaFX Runtime 2.0\lib\jfxrt.jar" SimpleFormFx.java
 * Execute: java -cp "C:\Program Files\Oracle\JavaFX Runtime 2.0\lib\jfxrt.jar";"Z:\test\javafx\mysql-connector-java-5.1.18\mysql-connector-java-5.1.18-bin.jar";. SimpleFormFx
 * ------------------------------
 * Test Data:
 * mysql -u testuser -p
 * mysql> select * from test.t1;
   +------+------------+
   | name | telephone  |
   +------+------------+
   | John | 4168889999 |
   | Tom  | 4161239999 |
   +------+------------+
   2 rows in set (0.00 sec)
 *--------------------------------
 */
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;
import javafx.scene.control.Button;
import javafx.geometry.Insets;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class SimpleFormFx extends Application {

   @Override
   public void start(Stage stage) {
    Group root = new Group();
    Scene scene = new Scene(root,300,200,Color.WHITE);
        Connection con;
        Statement stmt;
        ResultSet rs;
        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10, 10, 10, 10));
        vbox.setSpacing(10);
        // create a title, add it into vbox
        Text title = new Text("Simple Database Form in JavaFX");
        title.setFont(Font.font("Amble CN", FontWeight.BOLD, 12));
        vbox.getChildren().add(title);

        try {
            //connect to the database
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/","testuser","testpassword");
            // construct a sql statement, execute it and load resultset to rs
            stmt = con.createStatement();
            String sql = "select name,telephone from test.t1";
            rs = stmt.executeQuery(sql);

            if (rs != null) {
            // more controls in an array, add them into vbox
            ResultSetMetaData rsMetaData = rs.getMetaData();
            int numberOfColumns = rsMetaData.getColumnCount();
            rs.next();
            // get the column names into labels, fields into textfields, pack them into vbox
            for (int i = 1; i < numberOfColumns + 1; i++) {
              Label lbl= new Label(rsMetaData.getColumnName(i)+":");
              TextField txtField = new TextField(rs.getString(i));
              HBox hbox =new HBox(5);
              hbox.getChildren().addAll(lbl,txtField);
              vbox.getChildren().add(hbox);
            }
            }
        }
        catch (SQLException err) {
            System.err.println (err.getMessage());
        }

       // put VBox onto a border Pane
       BorderPane border = new BorderPane();
       border.setLeft(vbox);
       // add the border pane as a child
       root.getChildren().add(border);

       stage.setTitle("Simple Database Form in JavaFX");
       stage.setScene(scene);
       stage.show();
   }

   public static void main(String[] args) {
       launch(args);
   }
}
 

A program to simulate the Countdown Pedestrian Signals (CPS)

Countdown pedestrian signals (CPS) model is defined in Section 4E.02 of the 2009 Edition of the U.S. FHWA Manual on Uniform Traffic Control Devices with four indications (in fact only three can be used) presented in the following sequence:

  1. A steady WALKING PERSON (symbolizing WALK) signal indication means that a pedestrian facing the signal indication is permitted to start to cross the roadway in the direction of the signal indication, possibly in conflict with turning vehicles. The pedestrian shall yield the right-of-way to vehicles lawfully within the intersection at the time that the WALKING PERSON (symbolizing WALK) signal indication is first shown.
  2. A flashing UPRAISED HAND (symbolizing DONT WALK) signal indication means that a pedestrian shall not start to cross the roadway in the direction of the signal indication, but that any pedestrian who has already started to cross on a steady WALKING PERSON (symbolizing WALK) signal indication shall proceed to the far side of the traveled way of the street or highway, unless otherwise directed by a traffic control device to proceed only to the median of a divided highway or only to some other island or pedestrian refuge area.
  3. A steady UPRAISED HAND (symbolizing DONT WALK) signal indication means that a pedestrian shall not enter the roadway in the direction of the signal indication.
  4. A flashing WALKING PERSON (symbolizing WALK) signal indication has no meaning and shall not be used.

Thumbnail image of Figure 4E-1

This simulation program (output shown belows) simplifies the model into two main indications sequence (WALK and DON’T WALK). It demonstrates the techniques of rotation of image views and the implemtation of count down LED clock class in JavaFX. It can easily be changed to include the additional transition indication into the full three indications sequence in the official model.

Output of Pedestrian Signal Light Simulation with Countdown Clock

Output of Pedestrian Signal Light Simulation with Countdown Clock

The program takes the system clock and slices it into milli seconds for the count down pulses. The model also divides the ONE minute into two 30 seconds intervals: one 30 seconds for WALK and another 30 seconds for DONT WALK. It can be further enhanced with the pulse sounds if you like.

(Acknowledgement: Part of code of the clock class originates from Oracle’s digital clock sample).

PedestrianSignal.java

/**
 * Purpose: A program to simulate the pedestrian signal light
 *    with a thirty second count-down LED clock.
 * Resources: walk.jpg and dont_walk.jpg (you can download from anywhere on web)
 *
 * Author:  https://henry416.wordpress.com
 *
 * Compile: javac -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar" PedestriannSignal.java
 * Execute: java -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar";. PedestriannSignal
 */
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.effect.Effect;
import javafx.scene.effect.Glow;
import javafx.scene.effect.InnerShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.transform.Scale;
import javafx.scene.transform.Shear;
import javafx.util.Duration;
import java.util.Calendar;
 public class PedestrianSignal extends Application {
    private Clock clock;
    private Calendar calendar = Calendar.getInstance();
    private Image img_dont_walk = new Image("dont_walk.jpg");
    private Image img_walk = new Image("walk.jpg");
    private ImageView iv = new ImageView();

     @Override public void start(Stage stage) {
         calendar.setTimeInMillis(System.currentTimeMillis());
         int seconds = 60-calendar.get(Calendar.SECOND);
         Group root = new Group();
         Scene scene = new Scene(root);
         scene.setFill(Color.BLACK);
         VBox box = new VBox();

         // load the image
            if (seconds&gt;30)
              { iv.setImage(img_dont_walk);}
            else
              { iv.setImage(img_walk);}

         // resizes the image to have width of 120 while preserving the ratio and using
         // higher quality filtering method; this ImageView is also cached to
         // improve performance
         iv.setImage(img_walk);
         iv.setFitWidth(120);
         iv.setPreserveRatio(true);
         iv.setSmooth(true);
         iv.setCache(true);

         box.getChildren().add(iv);

         // add digital clock
         clock = new Clock(Color.ORANGERED, Color.rgb(50,50,50));
         clock.setLayoutX(45);
         clock.setLayoutY(186);
         clock.getTransforms().add(new Scale(0.83f, 0.83f, 0, 0));
         // add clock to bo
         box.getChildren().add(clock);
         root.getChildren().add(box);

         stage.setTitle("Pedestrian Test");
         stage.setWidth(120);
         stage.setHeight(300);
         stage.setScene(scene);
         stage.sizeToScene();
         stage.show();
     }
    public void play() {
        clock.play();
    }
    @Override public void stop() {
        clock.stop();
    }
    /**
     * Clock made of 6 of the Digit classes for hours, minutes and seconds.
     */
    public class Clock extends Parent {
        private Digit[] digits;
        private Timeline delayTimeline, secondTimeline;
        public Clock(Color onColor, Color offColor) {
            // create effect for on LEDs
            Glow onEffect = new Glow(1.7f);
            onEffect.setInput(new InnerShadow());
            // create effect for on dot LEDs
            Glow onDotEffect = new Glow(1.7f);
            onDotEffect.setInput(new InnerShadow(5,Color.BLACK));
            // create effect for off LEDs
            InnerShadow offEffect = new InnerShadow();
            // create digits
            digits = new Digit[2];
            for (int i = 0; i &lt; 2; i++) {
                Digit digit = new Digit(onColor, offColor, onEffect, offEffect);
                digit.setLayoutX(i * 80 + ((i + 1) % 2) * 20);
                digits[i] = digit;
                getChildren().add(digit);
            }
            // update digits to current time and start timer to update every second
            refreshClocks();
            play();
        }
        private void refreshClocks() {
            calendar.setTimeInMillis(System.currentTimeMillis());
            int seconds = 60-calendar.get(Calendar.SECOND);
            // load the image
            if (seconds&gt;30)
              { iv.setImage(img_dont_walk);}
            else
              { iv.setImage(img_walk);}

            if (seconds &gt;30)
              { seconds = seconds -30; }
            digits[0].showNumber(seconds / 10);
            digits[1].showNumber(seconds % 10);
        }
        public void play() {
            // wait till start of next second then start a timeline to call refreshClocks() every second
            delayTimeline = new Timeline();
            delayTimeline.getKeyFrames().add(
                    new KeyFrame(new Duration(1000 - (System.currentTimeMillis() % 1000)), new EventHandler&lt;ActionEvent&gt;() {
                        @Override public void handle(ActionEvent event) {
                            if (secondTimeline != null) {
                                secondTimeline.stop();
                            }
                            secondTimeline = new Timeline();
                            secondTimeline.setCycleCount(Timeline.INDEFINITE);
                            secondTimeline.getKeyFrames().add(
                                    new KeyFrame(Duration.seconds(1), new EventHandler&lt;ActionEvent&gt;() {
                                        @Override public void handle(ActionEvent event) {
                                            refreshClocks();
                                        }
                                    }));
                            secondTimeline.play();
                        }
                    })
            );
            delayTimeline.play();
        }
        public void stop(){
            delayTimeline.stop();
            if (secondTimeline != null) {
                secondTimeline.stop();
            }
        }
    }
    /**
     * Simple 7 segment LED style digit. It supports the numbers 0 through 9.
     */
    public static class Digit extends Parent {
        private static final boolean[][] DIGIT_COMBINATIONS = new boolean[][]{
                new boolean[]{true, false, true, true, true, true, true},
                new boolean[]{false, false, false, false, true, false, true},
                new boolean[]{true, true, true, false, true, true, false},
                new boolean[]{true, true, true, false, true, false, true},
                new boolean[]{false, true, false, true, true, false, true},
                new boolean[]{true, true, true, true, false, false, true},
                new boolean[]{true, true, true, true, false, true, true},
                new boolean[]{true, false, false, false, true, false, true},
                new boolean[]{true, true, true, true, true, true, true},
                new boolean[]{true, true, true, true, true, false, true}};
        private final Polygon[] polygons = new Polygon[]{
                new Polygon(2, 0, 52, 0, 42, 10, 12, 10),
                new Polygon(12, 49, 42, 49, 52, 54, 42, 59, 12f, 59f, 2f, 54f),
                new Polygon(12, 98, 42, 98, 52, 108, 2, 108),
                new Polygon(0, 2, 10, 12, 10, 47, 0, 52),
                new Polygon(44, 12, 54, 2, 54, 52, 44, 47),
                new Polygon(0, 56, 10, 61, 10, 96, 0, 106),
                new Polygon(44, 61, 54, 56, 54, 106, 44, 96)};
        private final Color onColor;
        private final Color offColor;
        private final Effect onEffect;
        private final Effect offEffect;
        public Digit(Color onColor, Color offColor, Effect onEffect, Effect offEffect) {
            this.onColor = onColor;
            this.offColor = offColor;
            this.onEffect = onEffect;
            this.offEffect = offEffect;
            getChildren().addAll(polygons);
            getTransforms().add(new Shear(-0.1,0));
            showNumber(0);
        }
        public void showNumber(Integer num) {
            if (num &lt; 0 || num &gt; 9) num = 0; // default to 0 for non-valid numbers
            for (int i = 0; i &lt; 7; i++) {
                polygons[i].setFill(DIGIT_COMBINATIONS[num][i] ? onColor : offColor);
                polygons[i].setEffect(DIGIT_COMBINATIONS[num][i] ? onEffect : offEffect);
            }
        }
    }
     public static void main(String[] args) {
         Application.launch(args);
     }
 }

Prototype Light Switch Program

lightSwitch.java

/*
   A small prototype for a switch-lights problem
   (four or more consecutive lights will be turned off)
   Henry Chen
   https://henry416.wordpress.com
*/

import java.io.*;
import javafx.application.*;
import javafx.scene.*;
import javafx.scene.paint.Color;
import javafx.stage.*;
import javafx.animation.*;
import javafx.util.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.geometry.*;
import javafx.scene.text.*;
import javafx.scene.shape.*;
import javafx.animation.*;
import java.lang.*;
import javafx.scene.input.*;
import javafx.event.*;

public class lightSwitch extends Application
{
   int[] array = new int[25];
   Circle[] light = new Circle[25];

   @Override
   public void start (Stage stage)
   {
      init(stage);
      stage.show();
   }

   public void init(Stage stage)
   {
      Group root = new Group();
      Scene scene = new Scene(root, 700, 500, Color.WHITE);
      for (int i = 0; i < 25; i++)
      {
         circleChange(i,root);
      }
      root.getChildren().addAll(light);
      stage.setTitle("Lights Problem");
      stage.setScene(scene);
   }

   public void circleChange(final int i, final Group root)
   {
      light[i] = new Circle(i*25 + 25, 100, 10);
      light[i].setOnMouseClicked(new EventHandler<MouseEvent>()
      {
         public void handle(MouseEvent me)
         {
            if (array[i] == 1)
               array[i] = 0;
            else
               array[i] = 1;

            int counter = 0;
            int place = -1;
            boolean x = false;
            for (int a = 0; a < 25; a++)
            {
               if (array[a] == 1)
               {
                  if (x == false)
                  {
                     place = a;
                     x = true;
                  }
                  counter++;
               }
               else
               {
                  if (counter >= 4 && x == true)
                     a = 26;
                  else
                  {
                     x = false;
                     counter = 0;
                     place = -1;
                  }
               }
            }

            if (counter >= 4 && x == true)
               for (int b = 0; b < counter; b++)
                  array[b+place] = 0;

            paint();
            me.consume();
         }
      });
   }

   public void paint()
   {
      for (int a = 0; a < 25; a++)
      {
         if (array[a] == 0)
            light[a].setFill(Color.BLACK);
         else
            light[a].setFill(Color.RED);
      }
   }

   public static void main (String args[])
   {
      Application.launch(args);
   }
}

Tab Test

TabTest.java

/**
 * An implementation of tabs using the TabPane class from Oracle
 *
 *  https://henry416.wordpress.com/
 *
 * Compile: javac -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar" TabTest.java
 * Execute: java -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar";. TabTest
 */
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.geometry.Side;
import javafx.scene.layout.BorderPane;
/**
 *
 * @see javafx.scene.control.TabPane
 * @see javafx.scene.control.Tab
 * @see javafx.scene.control.TabPane
 */
public class TabTest extends Application {
    private void init(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setScene(new Scene(root));
        primaryStage.setTitle("Tabs Test ");
        BorderPane borderPane = new BorderPane();
        final TabPane tabPane = new TabPane();
        tabPane.setPrefSize(400, 400);
        tabPane.setSide(Side.TOP);
        tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
        final Tab tab1 = new Tab();
        tab1.setText("Tab 1");
        final Tab tab2 = new Tab();
        tab2.setText("Tab 2");
        final Tab tab3 = new Tab();
        tab3.setText("Tab 3");
        final Tab tab4 = new Tab();
        tab4.setText("Tab 4");
        tabPane.getTabs().addAll(tab1, tab2, tab3, tab4);
        borderPane.setCenter(tabPane);
        root.getChildren().add(borderPane);
    }
    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }
}

MouseEvents Test

MouseEventsTest.java

/**
 * To test various mouse events and their usage. Click the
 * circles, drag them across the screen, resize them with the mouse wheel. All
 * mouse events are logged to the console.
 *
 *  https://henry416.wordpress.com/
 *
 * Compile: javac -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar" MouseEventsTest.java
 * Execute: java -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar";. MouseEventsTest
 */
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.event.EventHandler;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Point2D;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.ListView;
import javafx.scene.control.ListViewBuilder;
import javafx.scene.effect.InnerShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.RectangleBuilder;
/**
 * @see javafx.scene.Cursor
 * @see javafx.scene.input.MouseEvent
 * @see javafx.event.EventHandler
 */
public class MouseEventsTest extends Application {
    //create a console for logging mouse events
    final ListView<String> console = new ListView<String>();
    //create a observableArrayList of logged events that will be listed in console
    final ObservableList<String> consoleObservableList = FXCollections.observableArrayList();
    {
        //set up the console
        console.setItems(consoleObservableList);
        console.setLayoutY(305);
        console.setPrefSize(500, 195);
    }
    //create a rectangle - (500px X 300px) in which our circles can move
    final Rectangle rectangle = RectangleBuilder.create()
            .width(500).height(300)
            .fill(new LinearGradient(0, 0, 0, 1, true, CycleMethod.NO_CYCLE, new Stop[] {
                new Stop(1, Color.rgb(156,216,255)),
                new Stop(0, Color.rgb(156,216,255, 0.5))
            }))
            .stroke(Color.BLACK)
            .build();
    //variables for storing initial position before drag of circle
    private double initX;
    private double initY;
    private Point2D dragAnchor;
    private void init(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setResizable(false);
        primaryStage.setScene(new Scene(root, 500,500));
        primaryStage.setTitle("MouseEvents Test ");
        // create circle with method listed below: paramethers: name of the circle, color of the circle, radius
        Circle circleSmall = createCircle("Blue circle", Color.DODGERBLUE, 25);
        circleSmall.setTranslateX(200);
        circleSmall.setTranslateY(80);
        // and a second, bigger circle
        Circle circleBig = createCircle("Orange circle", Color.CORAL, 40);
        circleBig.setTranslateX(300);
        circleBig.setTranslateY(150);
        // we can set mouse event to any node, also on the rectangle
        rectangle.setOnMouseMoved(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                //log mouse move to console, method listed below
                showOnConsole("Mouse moved, x: " + me.getX() + ", y: " + me.getY() );
            }
        });
        // show all the circle , rectangle and console
        root.getChildren().addAll(rectangle, circleBig, circleSmall, console);
    }
    private Circle createCircle(final String name, final Color color, int radius) {
        //create a circle with desired name,  color and radius
        final Circle circle = new Circle(radius, new RadialGradient(0, 0, 0.2, 0.3, 1, true, CycleMethod.NO_CYCLE, new Stop[] {
            new Stop(0, Color.rgb(250,250,255)),
            new Stop(1, color)
        }));
        //add a shadow effect
        circle.setEffect(new InnerShadow(7, color.darker().darker()));
        //change a cursor when it is over circle
        circle.setCursor(Cursor.HAND);
        //add a mouse listeners
        circle.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                showOnConsole("Clicked on" + name + ", " + me.getClickCount() + "times");
                //the event will be passed only to the circle which is on front
                me.consume();
            }
        });
        circle.setOnMouseDragged(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                double dragX = me.getSceneX() - dragAnchor.getX();
                double dragY = me.getSceneY() - dragAnchor.getY();
                //calculate new position of the circle
                double newXPosition = initX + dragX;
                double newYPosition = initY + dragY;
                //if new position do not exceeds borders of the rectangle, translate to this position
                if ((newXPosition>=circle.getRadius()) && (newXPosition<=500-circle.getRadius())) {
                    circle.setTranslateX(newXPosition);
                }
                if ((newYPosition>=circle.getRadius()) && (newYPosition<=300-circle.getRadius())){
                    circle.setTranslateY(newYPosition);
                }
                showOnConsole(name + " was dragged (x:" + dragX + ", y:" + dragY +")");
            }
        });
        circle.setOnMouseEntered(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                //change the z-coordinate of the circle
                circle.toFront();
                showOnConsole("Mouse entered " + name);
            }
        });
        circle.setOnMouseExited(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                showOnConsole("Mouse exited " +name);
            }
        });
        circle.setOnMousePressed(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                 //when mouse is pressed, store initial position
                initX = circle.getTranslateX();
                initY = circle.getTranslateY();
                dragAnchor = new Point2D(me.getSceneX(), me.getSceneY());
                showOnConsole("Mouse pressed above " + name);
            }
        });
        circle.setOnMouseReleased(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                showOnConsole("Mouse released above " +name);
            }
        });
        circle.impl_setOnMouseWheelRotated(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent me) {
                //limit radius to <10, 60>
                double newRadius = circle.getRadius()+me.impl_getWheelRotation();
                if ((newRadius <= 60) && (newRadius >= 10)) {
                  //set new radius
                  circle.setRadius(newRadius);
                }
                showOnConsole("Mouse wheel rotated above " + name + ", with wheel rotation: " + me.impl_getWheelRotation() );
            }
        });
        return circle;
    }
    private void showOnConsole(String text) {
         //if there is 8 items in list, delete first log message, shift other logs and  add a new one to end position
         if (consoleObservableList.size()==8) {
            consoleObservableList.remove(0);
         }
         consoleObservableList.add(text);
    }
    public double getSampleWidth() { return 500; }
    public double getSampleHeight() { return 500; }
    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }
}

Key Event Test

KeyEventTest.java

/**
 * To demonstrate various key events and their usages (original from Oracle)
 *  https://henry416.wordpress.com/
 *
 * Compile: javac -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar" KeyEventsTest.java
 * Execute: java -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar";. KeyEventsTest
 */
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.PerspectiveTransform;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
/**
 * A sample that demonstrates various key events and their usage. Type in the
 * text box to view the triggered events: key pressed, key typed and key 
 * released. Pressing the Shift, Ctrl, and Alt keys also trigger events.
 *
 * @see javafx.scene.input.KeyCode
 * @see javafx.scene.input.KeyEvent
 * @see javafx.event.EventHandler
 */
public class KeyEventsTest extends Application {
  
    private void init(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setScene(new Scene(root));
        primaryStage.setTitle("Key Event Test");
        //create a console for logging key events
        final ListView<String> console = new ListView<String>(FXCollections.<String>observableArrayList());
        // listen on the console items and remove old ones when we get over 10 items
        console.getItems().addListener(new ListChangeListener<String>() {
            @Override public void onChanged(Change<? extends String> change) {
                while (change.next()) {
                    if (change.getList().size() > 10) change.getList().remove(0);
                }
            }
        });
        // create text box for typing in
        final TextField textBox = new TextField();
        textBox.setPromptText("Write here");
        textBox.setStyle("-fx-font-size: 34;");
        //add a key listeners
        textBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent ke) {
                console.getItems().add("Key Pressed: " + ke.getText());
            }
        });
        textBox.setOnKeyReleased(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent ke) {
                console.getItems().add("Key Released: " + ke.getText());
            }
        });
        textBox.setOnKeyTyped(new EventHandler<KeyEvent>() {
            public void handle(KeyEvent ke) {
                String text = "Key Typed: " + ke.getCharacter();
                if (ke.isAltDown()) {
                    text += " , alt down";
                }
                if (ke.isControlDown()) {
                    text += " , ctrl down";
                }
                if (ke.isMetaDown()) {
                    text += " , meta down";
                }
                if (ke.isShiftDown()) {
                    text += " , shift down";
                }
                console.getItems().add(text);
            }
        });
        VBox vb = new VBox(10);
        vb.getChildren().addAll(textBox, console);
        root.getChildren().add(vb);
    }
    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }
}

JavaFX2.0 Cursor Test

CursorTest.java

/**
 * To demonstrate changing the cursor icon from Oracle
 *  https://henry416.wordpress.com/
 *
 * Compile: javac -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar" CursorTest.java
 * Execute: java -cp "c:\progra~1\oracle\javafx runtime 2.0\lib\jfxrt.jar";. CursorTest
 */
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.TilePane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;

public class CursorTest extends Application {
    private void init(Stage primaryStage) {
        Group root = new Group();
        primaryStage.setScene(new Scene(root));
 primaryStage.setTitle("Cursor Test");
        TilePane tilePaneRoot = new TilePane(5, 5);
        tilePaneRoot.setHgap(2);
        tilePaneRoot.setVgap(2);
        tilePaneRoot.getChildren().addAll(
            createBox(Cursor.DEFAULT),
            createBox(Cursor.CROSSHAIR),
            createBox(Cursor.TEXT),
            createBox(Cursor.WAIT),
            createBox(Cursor.SW_RESIZE),
            createBox(Cursor.SE_RESIZE),
            createBox(Cursor.NW_RESIZE),
            createBox(Cursor.NE_RESIZE),
            createBox(Cursor.N_RESIZE),
            createBox(Cursor.S_RESIZE),
            createBox(Cursor.W_RESIZE),
            createBox(Cursor.E_RESIZE),
            createBox(Cursor.OPEN_HAND),
            createBox(Cursor.CLOSED_HAND),
            createBox(Cursor.HAND),
            createBox(Cursor.DISAPPEAR),
            createBox(Cursor.MOVE),
            createBox(Cursor.H_RESIZE),
            createBox(Cursor.V_RESIZE),
            createBox(Cursor.NONE)
        );
        root.getChildren().add(tilePaneRoot);
    }
    private Node createBox(Cursor cursor) {
        Label label = new Label(cursor.toString());
        label.setAlignment(Pos.CENTER);
        label.setPrefSize(85, 85);
        label.setStyle("-fx-border-color: #aaaaaa; -fx-background-color: #dddddd;");
        label.setCursor(cursor);
        return label;
    }
    @Override public void start(Stage primaryStage) throws Exception {
        init(primaryStage);
        primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }
}