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
}

About henry416
I am a computer technology explorer and an university student based on Toronto. If you have any question, please feel free to discuss and comment here

One Response to How to bind data from database with Java Swing UI

  1. Don Phelippe says:

    Yes, but where does the binding happen? if I change the data in a text field will it automatically be changed in the resultset? and then, will the change propagate to the database?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s