Login application using Java Swings and Mysql.

Front-end:Java Swings

Back-end:MySql

Class 1:Login JFrame

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class swing_sample extends JFrame
{
	//declaring our swing components
	JLabel l_name,l_pass;
	JTextField t_name;
	JPasswordField t_pass;     //A special JTextField but hides input text
	JButton button;
	Container c;

	//a inner class to handling ActionEvents
	handler handle;

	//a separate class for processing database connection and authentication
	database db;

	swing_sample()
	{
		super("Login form");

		c=getContentPane();
		c.setLayout(new FlowLayout());

		//extra classes
		db=new database();
	        handle =new handler();

                //swing components
		l_name=new JLabel("Username");
		l_pass=new JLabel("Password");
		t_name=new JTextField(10);
		t_pass=new JPasswordField(10);
		button=new JButton("Login");

		//adding actionlistener to the button
		button.addActionListener(handle);

		//add to contaienr
		c.add(l_name);
		c.add(t_name);
		c.add(l_pass);
		c.add(t_pass);
		c.add(button);
		//visual
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(200,130);

	}
	public static void main(String args[])
	{
		swing_sample sample=new swing_sample();
	}

	//an inner class .You can also write as a separate class
	class handler implements ActionListener
	{
		//must implement method
		//This is triggered whenever the user clicks the login button
		public void actionPerformed(ActionEvent ae)
		{
			//checks if the button clicked
			if(ae.getSource()==button)
			{
				char[] temp_pwd=t_pass.getPassword();
				String pwd=null;
				pwd=String.copyValueOf(temp_pwd);
				System.out.println("Username,Pwd:"+t_name.getText()+","+pwd);

				//The entered username and password are sent via "checkLogin()" which return boolean
				if(db.checkLogin(t_name.getText(), pwd))
				{
					//a pop-up box
					JOptionPane.showMessageDialog(null, "You have logged in successfully","Success",
                                        JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					//a pop-up box
					JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
                                        JOptionPane.ERROR_MESSAGE);
				}
			}//if
		}//method

	}//inner class
}//class

Class 2:Database

This is where the validation takesplace.
Connects to mysql and validates the username and pwd.

Note:Make sure you set the classpath to point the mysql_connector.jar file.The program wont work without it.

Download from mysql site by searching “Jconnector”.

import java.sql.*;
public class database 
{
	Connection con;
	PreparedStatement pst;
	ResultSet rs;
	database()
	{
		try{
			
			//MAKE SURE YOU KEEP THE mysql_connector.jar file in java/lib folder
			//ALSO SET THE CLASSPATH
			Class.forName("com.mysql.jdbc.Driver");
			con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ajax","root","");
                        pst=con.prepareStatement("select * from biodata where uname=? and pwd=?");
			
		   }
		catch (Exception e) 
		{
			System.out.println(e);
		}
	}
        //ip:username,password
        //return boolean
	public Boolean checkLogin(String uname,String pwd)
	{
		try {
                       
			pst.setString(1, uname); //this replaces the 1st  "?" in the query for username
			pst.setString(2, pwd);    //this replaces the 2st  "?" in the query for password
			//executes the prepared statement
			rs=pst.executeQuery();
			if(rs.next())
			{
				//TRUE iff the query founds any corresponding data
				return true;
			}
			else
			{
				return false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("error while validating"+e);
			return false;
		}
}

Output Screen:

 

Back:JFrame(Input window) Front:JOptionPane(confirmation window)

 

About PraveenMax
My Interests: ------------------ Java,Swings. Android,Python... And music

39 Responses to Login application using Java Swings and Mysql.

  1. illiana says:

    sir,
    am trying validation of users with java and mysql
    my code is working fine .but when both username and password is empty it goes to the next page directly it never shows cannot be logged in..
    please can you help me with this code
    thanking you in advance
    LoginDemo.java
    import javax.swing.*;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Rectangle;
    import java.awt.BorderLayout;
    //import java.awt.Dimension;
    import java.awt.event.KeyEvent;
    //import javax.swing.border.*
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;

    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;

    class LoginDemo extends JFrame
    {
    JButton SUBMIT;
    JLabel label1,label2;

    final JTextField text1,text2;
    LoginDemo()
    {
    setTitle(“Login Form”);
    setLayout(null);
    label1 = new JLabel();
    label1.setText(“Username:”);
    text1 = new JTextField(15);

    label2 = new JLabel();
    label2.setText(“Password:”);
    text2 = new JPasswordField(15);

    SUBMIT=new JButton(“SUBMIT”);
    label1.setBounds(350,100,100,20);
    text1.setBounds(450,100,200,20);
    label2.setBounds(350,130,100,20);
    text2.setBounds(450,130,200,20);
    SUBMIT.setBounds(450,160,100,20);
    add(label1);
    add(text1);
    add(label2);
    add(text2);
    add(SUBMIT);

    setVisible(true);
    setSize(1024,768);
    //ImageIcon image = new ImageIcon(“image.jpeg”);

    // JPanel.add(image, BorderLayout.North);
    SUBMIT.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae)
    {
    String value1=text1.getText();
    String value2=text2.getText();
    try{
    Class.forName(“com.mysql.jdbc.Driver”);
    Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/ttest”, “root”, “sasa”);
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery(“select * from lll where username='”+value1+”‘ and password='”+value2+”‘”);
    String uname=””,pass=””;
    String name=””,passs=””;
    if(rs.next()){
    uname=rs.getString(“username”);
    pass=rs.getString(“password”);
    name=rs.getString(null);
    passs=rs.getString(null);

    }

    if (value1.equals(uname) && value2.equals(pass)) {
    setVisible(false);
    System.out.println(“login successfull”);
    //showTreeView();
    NextPage page=new NextPage(uname);
    page.setVisible(true);

    }

    else{

    JOptionPane.showMessageDialog(null,”Incorrect login or password”,”Error”,JOptionPane.ERROR_MESSAGE);
    text1.setText(“”);
    text2.setText(“”);
    text1.requestFocusInWindow();
    }

    }

    catch(Exception e){}
    }
    });
    }

    public static void main(String arg[]){
    ImagePanel panel = new ImagePanel(new ImageIcon(“images/background.png”).getImage());

    JFrame frame = new JFrame();
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);

    new LoginDemo();
    }
    }
    class ImagePanel extends JPanel {

    private Image img;

    public ImagePanel(String img) {
    this(new ImageIcon(img).getImage());
    }

    public ImagePanel(Image img) {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
    }

    public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, null);
    }

    }

    please tell me what changes to be made so that when i just click on submit with empty fields it should show cannot be logged in

    NextPage.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;

    class NextPage extends JFrame
    {
    NextPage(String st)
    {
    setLayout(null);
    setDefaultCloseOperation(javax.swing. WindowConstants.DISPOSE_ON_CLOSE);
    setTitle(“Welcome”);
    JLabel lab=new JLabel(“Welcome “+st);
    JButton b=new JButton(“Logout”);

    lab.setBounds(10,10,500,20);
    b.setBounds(600,10,100,20);
    b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    LoginDemo demo=new LoginDemo();
    demo.setVisible(true);
    setVisible(false);
    }
    });
    add(lab);
    add(b);
    setSize(1024, 768);
    }
    }

    this is the nextpage once i login

  2. PraveenMax says:

    Now ur should work.I have made some modifications.But i recommend u to follow my code(in the blog) since ur way of swing coding is very dangerous(severe memory leaks ,many null references,unwanted imports,…).Just change the mysql login line to ur username and pwd.

    import javax.swing.*;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Rectangle;
    import java.awt.BorderLayout;
    //import java.awt.Dimension;
    import java.awt.event.KeyEvent;
    //import javax.swing.border.*
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;

    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;

    class LoginDemo extends JFrame
    {
    JButton SUBMIT;
    JLabel label1,label2;

    final JTextField text1,text2;
    LoginDemo()
    {
    setTitle(“Login Form”);
    setLayout(null);
    label1 = new JLabel();
    label1.setText(“Username:”);
    text1 = new JTextField(15);

    label2 = new JLabel();
    label2.setText(“Password:”);
    text2 = new JPasswordField(15);

    SUBMIT=new JButton(“SUBMIT”);
    label1.setBounds(350,100,100,20);
    text1.setBounds(450,100,200,20);
    label2.setBounds(350,130,100,20);
    text2.setBounds(450,130,200,20);
    SUBMIT.setBounds(450,160,100,20);
    add(label1);
    add(text1);
    add(label2);
    add(text2);
    add(SUBMIT);

    setVisible(true);

    setSize(800,300);
    //ImageIcon image = new ImageIcon(“image.jpeg”);

    // JPanel.add(image, BorderLayout.North);
    SUBMIT.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae)
    {
    String value1=text1.getText();
    String value2=text2.getText();
    //System.out.println(value1+”,”+value2);
    try{
    Class.forName(“com.mysql.jdbc.Driver”);
    Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/ttest”, “root”, “”);
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery(“select * from lll where username='”+value1+”‘ and password='”+value2+”‘”);
    String uname=””,pass=””;
    String name=””,passs=””;
    if(rs.next())
    {
    uname=rs.getString(“username”);
    pass=rs.getString(“password”);
    /*
    name=rs.getString(null);
    passs=rs.getString(null);
    */

    }

    if (value1.equals(uname) && value2.equals(pass))
    {
    setVisible(false);
    System.out.println(“login successfull”);
    //showTreeView();
    NextPage page=new NextPage(value1);
    page.setVisible(true);
    }

    else
    {

    JOptionPane.showMessageDialog(null,”Incorrect login or password”,”Error”,JOptionPane.ERROR_MESSAGE);
    text1.setText(“”);
    text2.setText(“”);
    text1.requestFocusInWindow();
    }

    }//try

    catch(Exception e){
    System.out.println(e.toString());
    }
    }
    });
    //DONT FORGET TO ADD THIS LINE.ELSE ,IT WILL EAT UR ENTIRE PC MEMORY
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String arg[]){
    ImagePanel panel = new ImagePanel(new ImageIcon(“src/python.jpg”).getImage());

    //WHY CREATING THIS JFRAME????
    /*JFrame frame = new JFrame();
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true); */

    new LoginDemo();
    }
    }
    class ImagePanel extends JPanel
    {

    private Image img;

    public ImagePanel(String img) {
    this(new ImageIcon(img).getImage());
    }

    public ImagePanel(Image img) {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
    }

    public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, null);
    }

    }

    class NextPage extends JFrame
    {
    NextPage(String st)
    {
    setLayout(null);
    setDefaultCloseOperation(javax.swing. WindowConstants.DISPOSE_ON_CLOSE);
    setTitle(“Welcome”);
    JLabel lab=new JLabel(“Welcome”+st);
    JButton b=new JButton(“Logout”);

    lab.setBounds(10,10,500,20);
    b.setBounds(600,10,100,20);
    b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    LoginDemo demo=new LoginDemo();
    demo.setVisible(true);
    setVisible(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//dont forget this line for all JFrame!!
    }
    });
    add(lab);
    add(b);
    setSize(1024, 768);
    }
    }

    • illiana says:

      Sir,
      Thanks A lot for the reply
      But still it logs in with empty fields.wherein it is supposed to show user cannot be logged in.
      i just need a condition wherein it should not allow users to view next page with empty fields.Otherwise for valid users which are stored in database it validates successfully and evn for non valid users also it shows cannot be logged in. I will be thank ful to you if you can help me with this.

      thanking you in advance

      • PraveenMax says:

        lol..i forgot to paste the updated code…Anyway,will tell the main part to be modified.

        just remove the 2 lines(The 4 string variables) after the “ResultSet” lines.and
        just put two string variables .

        Like this,
        String uname=null,pass=null;

        Previously u have written like,
        String uname=””,pass=””;
        You just using the same variable for storing fetched data from db and also for storing empty string(idk y u want to store empty string).And so it allows logging in even if it checked with db.
        Now it should work PERFECTLY as a expect…:-)

  3. illiana says:

    Sir,
    actually am having difficulty in making my project into a jar in netbeans.
    I could get the jar file .But the libraries what i imported are not getting added..Could you please help me with the steps for making project into a jar??
    thank you

    • PraveenMax says:

      Are you trying to create a executable jar file ?Which libraries u r importing?I dont know abt netbeans.but any thg in eclipse.

      • illiana says:

        yeah am trying to create executable jar file…..i want jmf jar files to be imported to my project..but its not happening…normally my project works if i run on netbeans

        • PraveenMax says:

          hmmm….there should be some options such as “create runnable jar” within netbeans.i know how to do that in eclipse.Since u have done in netbeans , i dont know abt that

  4. illiana says:

    ok sir,can you please tell me how to do that in eclipse and also let me know how to add jars i tht?

  5. Thomas says:

    Class.forName(“com.mysql.jdbc.Driver”);
    con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/mercury”,”root”,””);
    pst=con.prepareStatement(“select * from auth_user where username=? and password=?”);

    Hi,
    My database name mercury and table name auth_user, trying to connect but not able to do you have some suggestions please. Thank you in advance.

  6. PraveenMax says:

    Do these checks,
    1.Make sure that you have mysql jar file in your classpath.
    2.Check whether mysql instance is running or not by logging in from cmd-prompt.
    >> mysql -uroot -p(your pwd).
    3.Double check whether you are entering the correct password.
    If everything goes well,execute some basic queries and then proceed with your login process.

  7. Aby Paul says:

    GetConnection.java
    ===============================
    package dao;

    import java.sql.*;

    public class GetConnection{

    public Connection getConnection() throws Exception
    {

    Connection con=null;
    try {

    System.out.println(“MySQL Connect Example.”);

    String url = “jdbc:mysql://localhost:3306/”;
    String dbName = “shopms”;
    String driver = “com.mysql.jdbc.Driver”;
    //Accessing driver from the jar file
    Class.forName(driver).newInstance();
    //Creating a veriable for Connection Called conn
    con = DriverManager.getConnection(url+dbName,”root”,””);

    } catch (Exception e) {
    e.printStackTrace();
    }
    return con;

    }

    public static void main(String arg[])
    {
    GetConnection con =new GetConnection();
    System.out.println(“Connection”+con);

    }

    }
    ===================================================================

    FrmLogin.java
    ====================================================================
    package sms;

    * Title: Login Panel *

    import javax.swing.*;

    public class FrmLogin {

    private JFrame frame;
    private JTextField t_Uname;
    private JPasswordField t_Passfield;
    private JComboBox combUsertype;
    private JButton btnLogon;

    //a inner class to handling ActionEvents
    handler handle;

    //a separate class for processing database connection and authentication
    GetConnection gc;
    PreparedStatement pst=null;
    ResultSet rs=null;

    /**
    * Launch the application.
    */
    public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
    public void run() {
    try {
    FrmLogin window = new FrmLogin();
    window.frame.setVisible(true);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    });
    }

    /**
    * Create the application.
    */
    private FrmLogin() {
    //super(“Login form”);

    handle =new handler();

    frame = new JFrame();
    frame.setBounds(100, 100, 350, 250);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JLabel lblNewLabel = new JLabel(“User Name”);
    lblNewLabel.setBounds(50, 50, 75, 25);
    frame.getContentPane().add(lblNewLabel);

    JLabel lblNewLabel_1 = new JLabel(“Password”);
    lblNewLabel_1.setBounds(50, 80, 75, 25);
    frame.getContentPane().add(lblNewLabel_1);

    JLabel lblNewLabel_2 = new JLabel(“User Type”);
    lblNewLabel_2.setBounds(50, 110, 75, 25);
    frame.getContentPane().add(lblNewLabel_2);

    t_Uname = new JTextField();
    t_Uname.setToolTipText(“Enter Your Username”);
    t_Uname.setBounds(125, 50, 125, 20);
    frame.getContentPane().add(t_Uname);
    t_Uname.setColumns(10);

    t_Passfield = new JPasswordField();
    t_Passfield.setToolTipText(“Enter Your Password”);
    t_Passfield.setBounds(125, 80, 125, 20);
    frame.getContentPane().add(t_Passfield);

    combUsertype = new JComboBox();
    combUsertype.setModel(new DefaultComboBoxModel(new String[] {“Admin”, “Staff”}));
    combUsertype.setToolTipText(“Select Your Usertype”);
    combUsertype.setBounds(125, 110, 125, 20);
    frame.getContentPane().add(combUsertype);

    btnLogon = new JButton(“Logon”);
    btnLogon.setToolTipText(“Press In Logon “);
    btnLogon.addActionListener(handle);
    btnLogon.setBounds(175, 140, 75, 20);
    frame.getContentPane().add(btnLogon);

    }

    //An inner class .You can also write as a separate class
    class handler implements ActionListener
    {

    //must implement method
    //This is triggered whenever the user clicks the login button
    public void actionPerformed(ActionEvent ae)
    {

    //checks if the button clicked
    if(ae.getSource()== btnLogon)
    {
    char[] temp_pwd=t_Passfield.getPassword();
    String Pwd=null;
    Pwd=String.copyValueOf(temp_pwd);
    System.out.println(“Username,Pwd:”+t_Uname.getText()+”,”+Pwd);

    //The entered username and password are sent via “checkLogin()” which return boolean
    if(checkLogin(t_Uname.getText(), Pwd))
    {
    //a pop-up box
    JOptionPane.showMessageDialog(null, “You have logged in successfully”,”Success”,
    JOptionPane.INFORMATION_MESSAGE);
    }
    else
    {
    //a pop-up box
    JOptionPane.showMessageDialog(null, “Login failed!”,”Failed!!”,
    JOptionPane.ERROR_MESSAGE);
    }
    }//if
    }//method

    }//inner class

    public Boolean checkLogin(String uname,String pwd)
    {

    try {

    String sql = “select uname, pwd from login where uname=? and pwd=?”;
    System.out.println(“SQL…………” +sql);
    pst=gc.getConnection().prepareStatement(sql);
    System.out.println(“!!!!!!!!!!!!!!”);
    pst.setString(1, uname); //this replaces the 1st “?” in the query for username
    pst.setString(2, pwd); //this replaces the 2st “?” in the query for password
    //executes the prepared statement
    rs=pst.executeQuery();

    System.out.println(“@@@@@@@@@”+rs);
    if(rs.next())
    {
    //TRUE iff the query founds any corresponding data
    return true;
    }
    else
    {
    return false;
    }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    System.out.println(“error while validating”+e);
    return false;
    }
    }

    }
    ====================================================

    My DB Details
    ==================
    uid uname pwd utype
    ===============================

    I got running time error please help me

    Error is ::::::::

    SQL…………select uname, pwd from login where uname=? and pwd=?
    error while validatingjava.lang.NullPointerException

    • PraveenMax says:

      Hey there, the problem with your code (apart from being hard to read) is that you didnt create an instance of the necessary class before accessing it. That’s why it is showing NullPointerException.

      In your formlogin.java, you have tried to invoke a GetConnection class’s method inside “checkLogin(String uname,String pwd)” without creating an instance for it.

      Solution:
      ————–
      1.in your formlogin.java, change the line
      GetConnection gc;
      to
      GetConnection gc=new GetConnection();

      It will work for sure.. :-)

  8. Kavita says:

    Sir, I want to know whether we can connect java swing application to the remote Database server i.e can we make it client server application (different machines having application installed and one database server )

    • PraveenMax says:

      Yes, you can do that. Just do the following,
      1. Specify the correct database driver name of the remote machine in this line.
      Class.forName(“com.mysql.jdbc.Driver”);

      2. Then specify the ip-address or url of the remote machine.
      con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/ajax”,”root”,””);

      Make sure you are able to access the remote database from the machine in which the swing application runs.

  9. rodh says:

    sir i think these is not working in JCreator hehe ,,,,

  10. rodh says:

    sir how can i run these in JCreator

  11. Thanh Nguyen says:

    Sir, I need your help! I got a problem with my program. I tried to implement your way of creating the Log-in form for my school project but it keep giving me errors.

    My codes is here: tny.cz/b873679a

    • PraveenMax says:

      Hello,
      You have made the following error,

      1. There is no “public static void main(String[] args)” and so your code will never execute.
      Solution: Add that method in “logInMenu” class and create an instance.

      public static void main(String[] args)
      {
      new logInMenu();
      }
      2. In “logInMenu” class, you are trying to invoke a method on an uninitialized variable “dbC”.
      Solution: Add this line ,
      dbConnect dbC=new dbConnect();

      I have already made those changes in your code.Just change the db attributes to your needs.
      Get it from here ,
      https://gist.github.com/anonymous/5239589

      • Thanh Nguyen says:

        thank you very much

      • Thanh Nguyen says:

        One more question if you dont mind.
        For example, after successful log in, the program will open a new form (a new class),
        how do i use the data the user used in that class? for example “username”

        My attempt:
        in another class, for example Class X:
        …….
        dbConnect db = new dbConnect();
        System.out.println(“Username: ” + db.uname);
        System.out.println(“Password: ” + db.pword);
        ……..

  12. Naru says:

    Sir, I got the code to work perfectly fine on my computer but after I exported it in eclipse and tried to run it on another computer, the log in runs but doesn’t seem to connect to database? What am I missing here? Please help, thanks

    • PraveenMax says:

      Check whether you have mentioned the correct db name in code and also the username,password details.

      • Naru says:

        I’ve checked and I still don’t know what’s wrong.

        my code is here: http://tny.cz/2aef0942

        It gets stuck right after printing driver in place.
        I don’t know if it’s the j connector library or my code or the export or something else.

        • PraveenMax says:

          Paste the stack trace. Your link is missing other codes.

          • Naru says:

            ok so judging from trace, nothing wrong with the code, its my database setting. I’ve read in some site saying localhost is not meant to be able externally accessed normally and has to be set up through .config or .ini.

            Now I’m not sure if that site is correct because I am a complete database newbie but if it is, do you know any guide/site that will teach me how to make this local database accessible from another computer? Probably in step starting right after downloading mysql-5.6.10-winx64.zip

            thanks

            Communications link failure

            The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
            com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

            The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
            at java.lang.reflect.Constructor.newInstance(Unknown Source)
            at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
            at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
            at com.mysql.jdbc.MysqlIO.(MysqlIO.java:355)
            at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2479)
            at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2516)
            at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2301)
            at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:834)
            at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
            at java.lang.reflect.Constructor.newInstance(Unknown Source)
            at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
            at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
            at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317)
            at java.sql.DriverManager.getConnection(Unknown Source)
            at java.sql.DriverManager.getConnection(Unknown Source)
            at LoginDemo$1.actionPerformed(LoginDemo.java:68)
            at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
            at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
            at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
            at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
            at java.awt.Component.processMouseEvent(Unknown Source)
            at javax.swing.JComponent.processMouseEvent(Unknown Source)
            at java.awt.Component.processEvent(Unknown Source)
            at java.awt.Container.processEvent(Unknown Source)
            at java.awt.Component.dispatchEventImpl(Unknown Source)
            at java.awt.Container.dispatchEventImpl(Unknown Source)
            at java.awt.Component.dispatchEvent(Unknown Source)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
            at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
            at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
            at java.awt.Container.dispatchEventImpl(Unknown Source)
            at java.awt.Window.dispatchEventImpl(Unknown Source)
            at java.awt.Component.dispatchEvent(Unknown Source)
            at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
            at java.awt.EventQueue.access$200(Unknown Source)
            at java.awt.EventQueue$3.run(Unknown Source)
            at java.awt.EventQueue$3.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
            at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
            at java.awt.EventQueue$4.run(Unknown Source)
            at java.awt.EventQueue$4.run(Unknown Source)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
            at java.awt.EventQueue.dispatchEvent(Unknown Source)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
            at java.awt.EventDispatchThread.run(Unknown Source)
            Caused by: java.net.ConnectException: Connection refused: connect
            at java.net.DualStackPlainSocketImpl.connect0(Native Method)
            at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
            at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
            at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
            at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
            at java.net.PlainSocketImpl.connect(Unknown Source)
            at java.net.SocksSocketImpl.connect(Unknown Source)
            at java.net.Socket.connect(Unknown Source)
            at java.net.Socket.connect(Unknown Source)
            at java.net.Socket.(Unknown Source)
            at java.net.Socket.(Unknown Source)
            at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:259)
            at com.mysql.jdbc.MysqlIO.(MysqlIO.java:305)
            … 51 more

            • PraveenMax says:

              First check whether you can access the host computer by using ping commands. then check whether the mysql service is running on host computer. finally, specify the ip address instead of localhost in the code.

  13. Raj says:

    Sir, help me.
    Grant me with a project on library management system using Java Swing.
    Please.It’s my last tomorrow for submission.
    rajmehta629@gmail.com

  14. Isaac says:

    I believe this login is generalized! Supposing you want to login in users based on a certain criteria, that acts much like a session? Each user logs into his/her profiled based on individual usernames and passwords!

  15. Isaac says:

    @PraveenMax:
    I stumbled into your blog while searching for help on Java Swing login form authentication, and I must thank you for your posts proved very helpful indeed! Thanks a lot!

  16. Isaac says:

    I have 2 requests to make though:
    My first request is this: After using the login form successfully, my program transfered focus to the appropriate GUI.. now my intention is to select a user’s profiled based on the login information.. how do i get the called GUI to display profile information based on the information submitted at login?

    My Second Request is that am finding it difficult to create 2 dynamic JComboBox, where the second JComboBox’s items change based on what was selected in the first comboBox. This is what I have done:

    brandCombo.setMaximumRowCount(10);
    brandCombo.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
    try{
    try{
    Class.forName(“com.mysql.jdbc.Driver”).newInstance();
    }catch(Exception e){
    JOptionPane.showMessageDialog(null, “Exception: “+e.getMessage());
    }
    Connection con = java.sql.DriverManager.getConnection(“jdbc:mysql://localhost:3306/phoneshopsystem”,”root”, dbLogin.db());
    String query2 = “SELECT phoneModels FROM phones WHERE phoneBrand = ?”;
    PreparedStatement pst = con.prepareStatement(query2);
    brandCombo = (JComboBox)ae.getSource();
    String b = brandCombo.getSelectedItem().toString();
    pst.setString(2, b);
    ResultSet rset = pst.executeQuery();
    if(rset.next()){
    String itemsIn = rset.getString(3);
    phoneModelCombo.setModel(new DefaultComboBoxModel());
    phoneModelCombo.addItem(itemsIn);
    }
    new dbLogin().closeDB();
    }catch(SQLException sql){
    }
    }
    });

    brandCombo is the first JComboBox which has already been initialized with items, and phoneModelCombo is the second JComboBox which is supposed to be initialized with items based on what is selected in brandCombo.

    • PraveenMax says:

      For your 1st issue, create a separate JPanel for each profile and attach it to jframe when appropriate user logged in.
      For 2nd issue, create a new jcombobox and add to the container instead of updating the existing jcombobox. It is somewhat a hack but works.

      • Isaac says:

        Am not sure i fully grasp the meaning of your second comment, buh thanks!I guess What i need to do is add an ItemListener on the first ComboBox, not the second, as mentioned in my request. Thanks again for your response!!!!!

  17. Isaac says:

    Thanks in advance!

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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: