Thursday, May 17, 2012

A simple Login Screen in java with database Connectivty and Validation


import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class loginframe extends JFrame implements ActionListener
{
JLabel l1,l2,l3,l4;
JTextField t1,t2;
JButton b1,b3;
Connection cn;
PreparedStatement pst;
ResultSet rs;
Panel p1,p2;
Container cp;
public loginframe()
{
super("Login form");
cp=getContentPane();
l1=new JLabel("Enter username");
l1.setForeground(Color.blue);
l2=new JLabel("Enter password");
l2.setForeground(Color.blue);
l3=new JLabel("                 ");
t1=new JTextField(20);
t1.setFont(new Font("Comic Sans MS",Font.BOLD,15));

    t2=new JTextField(20);
   
    t2.setFont(new Font("Comic Sans MS",Font.BOLD,15));
   
     t2=new JPasswordField(10);

     p1=new Panel();
p1.setLayout(new GridLayout(3,2));
p1.add(l1);p1.add(t1);
p1.add(l2);p1.add(t2);
p1.add(l3);
b1=new JButton("Login");
b1.addActionListener(this);
b1.setForeground(Color.green);
b1.setBackground(Color.black);
b1.setFont(new Font ("Comic Sans MS",Font.BOLD ,20));

b3=new JButton("clear");
b3.addActionListener(this);
b3.setForeground(Color.green);
b3.setBackground(Color.black);
b3.setFont(new Font ("Comic Sans MS",Font.BOLD ,20));
p2=new Panel();
p2.setLayout(new FlowLayout());
p2.add(b1);p2.add(b3);
//setFont(new Font("Dialog",Font.BOLD,20));

cp.add(p1,BorderLayout.NORTH);
cp.add(p2,BorderLayout.SOUTH);

setSize(300,300);
cp.setBackground(Color.pink);

setVisible(true);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver is loaded");
cn=DriverManager.getConnection("jdbc:odbc:proj");
System.out.println("Connection established");
pst=cn.prepareStatement("select * from logintab where username=?");
}
catch(Exception e)
{
System.out.println("Exception 1");
}
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b3)
{
t1.setText(" ");
t2.setText("");
l3.setText(" ");
}
else
{
try
{
pst.setString(1,t1.getText());
rs=pst.executeQuery();
if(rs.next())
{

if(t2.getText().equals( rs.getString(2)))
{
new menu();
}
else
l3.setText("Wrong password");
}
else
l3.setText("Wrong Username");
rs.close();

}//try
catch(SQLException e)
{
System.out.println(" sql exception ");
}
}//else
}//action
protected void finalize()
{
try
{
pst.close();
cn.close();
}
catch(Exception e)
{
System.out.println("exception 3");
}
}
public static void main(String arg[])
{
new loginframe();
loginframe l=new loginframe();
l.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{ System.exit(0); }});
}
           
}






4 comments:

  1. Nice 1 Chinmay....
    I'll implement it soon in my project...
    U cn visit my blog for sm technical stuff: http://g2chauhan.blogspot.in/

    ReplyDelete
  2. thanx yar n keep sugesting me..

    ReplyDelete