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);
   }
}
 

How to bind data from database with Java Swing UI

I have the following data in a PostgreSQL database called ‘mydb’ on Linux.

~$ psql mydb
psql (8.4.9)
Type "help" for help.

mydb=# select * from employees;
 id |   lastname   | firstname | department
----+--------------+-----------+------------
  1 | Werner       | Max       |          1
  2 | Lehmann      | Daniel    |          2
  3 | Roetzel      | David     |          1
  4 | Scherfgen    | David     |          2
  5 | Kupfer       | Andreas   |          2
  6 | Scheidweiler | Najda     |          2
  7 | Jueppner     | Daniela   |          4
  8 | Hasse        | Peter     |          4
  9 | Siebigteroth | Jennifer  |          3
(9 rows)

mydb=# select * from departments;
 id |    name    
----+------------
  1 | Management
  2 | R&D
  3 | Marketing
  4 | Accounting
(4 rows)

mydb=# select firstname, lastname, name
mydb-# from employees, departments
mydb-# where employees.department = departments.id;
 firstname |   lastname   |    name    
-----------+--------------+------------
 David     | Roetzel      | Management
 Max       | Werner       | Management
 Najda     | Scheidweiler | R&D
 Andreas   | Kupfer       | R&D
 David     | Scherfgen    | R&D
 Daniel    | Lehmann      | R&D
 Jennifer  | Siebigteroth | Marketing
 Peter     | Hasse        | Accounting
 Daniela   | Jueppner     | Accounting
(9 rows)

mydb=#

The following is the Java program which consists of two parts: the bottom part  (initComponents()) is the UI generated by using the Netbean IDE, and the upper part is the java program (DoConnect() ) to connect to a database mydb in PostgreSQL, and run a query, and then bind the data (first record) to the text fields on the UI.  (Basically, it should work with all the JDBC compliance DB like mysql, derby, Oracle, Sybase, UDB or Microsoft SQL. Just replace the connection string, and put the relevant JDBC driver jar file in the classpath. Also, the compile and execute command are for Linux.)

SimpleForm (Data Binding Using Java Swing)
SimpleForm (Data Binding Using Java Swing)
SimpleForm.java 
/*
 Written by: https://henry416.wordpress.com/
 to compile: javac -cp /usr/share/java/postgresql.jar SimpleForm.java
 to execute: java -cp /usr/share/java/postgresql.jar:. SimpleForm
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class SimpleForm extends javax.swing.JFrame {
    Connection con;
    Statement stmt;
    ResultSet rs;
    /** Creates new form SimpleForm */
    public SimpleForm() {
        initComponents();
        DoConnect();
    }
    public void DoConnect( ) {
        try {
            //connect to the database
            con = DriverManager.getConnection("jdbc:postgresql:mydb","testuser","testpassword");
            // construct a sql statement, execute it and load resultset to rs
            stmt = con.createStatement();
            String sql = "select firstname, lastname, name from employees, departments where employees.department = departments.id";
            rs = stmt.executeQuery(sql);
            // retrieve the fields from rs to txtFields
   rs.next();
            txtFirst.setText(rs.getString("firstname"));
            txtLast.setText(rs.getString("lastname"));
            txtDept.setText(rs.getString("name"));
        }
        catch (SQLException err) {
            JOptionPane.showMessageDialog(SimpleForm.this, err.getMessage());
        }
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SimpleForm().setVisible(true);
            }
        });
    }
 /*
  The following is GUI generated from Netbean
 */
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        txtFirst = new javax.swing.JTextField();
        txtLast = new javax.swing.JTextField();
        txtDept = new javax.swing.JTextField();
        lblFirst = new javax.swing.JLabel();
        lblLast = new javax.swing.JLabel();
        lblDept = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        lblFirst.setText("First Name:");
        lblLast.setText("Last Name");
        lblDept.setText("Department:");
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblDept)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtDept, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtFirst, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblFirst))
                                .addGap(42, 42, 42)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblLast)
                                    .addComponent(txtLast, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap(81, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFirst)
                    .addComponent(lblLast))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtLast, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFirst, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addComponent(lblDept)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtDept, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(120, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>

    // Variables declaration - do not modify
    private javax.swing.JLabel lblDept;
    private javax.swing.JLabel lblFirst;
    private javax.swing.JLabel lblLast;
    private javax.swing.JTextField txtDept;
    private javax.swing.JTextField txtFirst;
    private javax.swing.JTextField txtLast;
    // End of variables declaration
}

Java MySQL Test

First Test
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Example1 {

    public static void main(String[] argv) {
      Connection conn = null;      
      try {
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/",
                                        "user","pwd");
      } catch (SQLException se) {
        System.out.println("Couldn't connect: print out a stack trace and exit.");
        se.printStackTrace();
        System.exit(1);
      }

          System.out.println("Connected to database");
      if (conn != null)
        System.out.println("We connected to the database! Let's select some data.");
      else
        System.out.println("We should never get here.");

      try {
         // processing a simple query
        Statement st = conn.createStatement();
         //by default it fetches all the rows st.setFetchSize(0)
        // conn.setAutoCOmmit(false);
        // st.setFetchSize(50);
        ResultSet rs = st.executeQuery("Select name,tel from test.contact");

        while (rs.next()) {
            System.out.print("Name=");
            System.out.println(rs.getString(1));
            System.out.print("Tel=");
            System.out.println(rs.getString(2));        }
        
      } catch (SQLException se) {
            System.out.println("Couldn't process a query: print out a stack trace and exit.");
            se.printStackTrace();
            System.exit(1);              
      }
    }

}

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);
     }
 }

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); }
}
Design a site like this with WordPress.com
Get started