I don’t know about you but this is an exciting Friday for me. I’m all smiles :-). The picture above is an actual screenshot of what I’ve been working on yesterday. I didn’t mention that I finally completed the Java: A Beginners Guide book did I? Actually I did! Haha, It has been a gruesome journey, lots of despair and losing hope but it has been quite fun. I have already forgotten most of what I have learnt, but now I can comfortably read Java code and create small programs. It is really exciting to achieve something. I am not where I want to be, but at least I am assured that I am on my way there!

Today I would like to share how I created this simple signup page. I won’t really get into the nitty gritty details, because I’m not sure if there’s anybody interested anyway, so I’ll just give an overview of how I pieced up everything and finally came up with this signup page. But if there’s someone reading this and would like some clarification, well you can comment below and I promise I’ll outline all the steps, one by one.signup2

Before I begin, this page is created entirely on Java Swing. When yo
u add details into the text fields, they are stored into a Database, this is achieved using MySql (yes, I have been studying SQL too). Here is an image of the page:

Here is how you do it:

  • Download MySQL workbench and Install.
  • Create a new schema, call it “demo”, add a table, call it “loginaccount”. This is where the details will be stored.
  • In this table, create 4 columns, the id(primary key), username,password & ts(timestamp).
  • After you are done, save the database.
  • Open Eclipse Ide, and create 2 classes; “Connectivity.java” and “NewUser.java”.
  • The connectivity class will be used to connect the application to MySql.
  • Before you continue, you have to download Mysql connector for Java, JDBC and install it, (there’s a great tutorial for that on youtube).
  • Here are the source codes for the 2 classes:

Connectivity.java:


//import statements
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;</pre>
//Create class conectivity
public class Connectivity {

//JDBC Driver name and database url
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL = "jdbc:mysql://localhost/demo";

//Database credentials
static final String USER = "root";
static final String PASS = "mathenge24";

//main method
public static void main(String[]args) {

//Create object of connection and define it null
Connection conn = null;

//try block
try {
//Step 2: Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");

//Step 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

//Print success message
System.out.println("Connected to database successfully...");
} catch(SQLException exc) {
//Handle errors
exc.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(conn!=null)
conn.close();
} catch(SQLException exc) {
exc.printStackTrace();
}
}
}
}
<pre>

 

NewUser.java:

</pre>
//Import statements
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Wrapper;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

//Create the class
public class NewUser extends JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;

//Declare variables
private JPanel contentPane;
private JTextField txtUser;
private JButton btnSignup;
private JTextField txtPassword;
protected java.lang.String Spassword;

//Database URL
static final String DB_URL = "jdbc:mysql://localhost/demo";

//Database Credentials
static final String USER = "root";
static final String PASS = "mathenge24";
protected static final String String = null;

/*
* Launch the Application
*/

public static void main(String[]args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NewUser frame = new NewUser();
frame.setVisible(true);
} catch(Exception exc) {
exc.printStackTrace();
}
}
});
}

/*
* Create the frame
*/

//Create a constructor
public NewUser() {

//setTitle
setTitle("New User Login");

//Set close operation
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//set bounds of frame
setBounds(100, 100, 450, 300);

//Create JPanel Object
contentPane = new JPanel();

//Set contentpane border
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

//set ContentPane with new object
setContentPane(contentPane);

//set contentpane layout as null
contentPane.setLayout(null);

//Create text field for user
txtUser = new JTextField();

//set bounds for text field
txtUser.setBounds(160, 51, 99, 20);

//Add the textfield to the contentpane
contentPane.add(txtUser);

//Set column for text field
txtUser.setColumns(10);

//Lable the Username text field
JLabel lblUserName = new JLabel("User Name");

//Set bounds for label
lblUserName.setBounds(70, 54, 86, 14);

//Lable the Password text field
JLabel lblPasswrd = new JLabel("PassWord");

//Set bounds for label
lblPasswrd.setBounds(70, 110, 86, 14);

//Add Username label into contentpane
contentPane.add(lblUserName);

//Add Password label into contenpane
contentPane.add(lblPasswrd);

//Create Signup button
btnSignup = new JButton("SignUp");

//Add event handler on signup button
btnSignup.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

//Create Wrapper object and define as Null
Wrapper conn = null;

try {

//declare variables
String username = "";
String password = "";

//Get values
username = txtUser.getText().trim();
password = txtPassword.getText().trim();

//Check if the field is blank
if (username.equals("") || password.equals("")) {
JOptionPane.showMessageDialog(null," Invalid Name or Password","Error",JOptionPane.ERROR_MESSAGE);

} else {
String IQuery = "INSERT INTO `demo`.`loginaccount`(`username`,`password`,`ts`) VALUES('"+username+"', '"+password+"',current_timestamp)";
System.out.println(IQuery);
System.out.println("Connecting to a selected database...");

//Open a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected to database successfully...");

//select the rows
((Connection)conn).createStatement().execute(IQuery);

//define sMessage variable
String SMessage = "Record added for " + username;

//Create dialog box to printout the above
JOptionPane.showMessageDialog(null,SMessage,"Message",JOptionPane.PLAIN_MESSAGE);

//Close connection
((java.sql.Connection)conn).close();
}
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception exc) {
exc.printStackTrace();
}

}
});
//set bound for SignUp button
btnSignup.setBounds(131, 165, 89, 23);

//add button into contentPane
contentPane.add(btnSignup);

//create text field for password
txtPassword = new JTextField();

//set bound for password field
txtPassword.setBounds(160, 106, 99, 20);

//add text field on contentPane
contentPane.add(txtPassword);

//set column for password text field
txtPassword.setColumns(10);

}
}
<pre>

That’s it :-). The above will create a JFrame, with Jbutton, JTextfield & JLabel, all these are Swing objects.

I’ll be posting source codes for the projects I undertake, maybe they’ll help someone somewhere, someday.

Advertisements