Solved

create a login form in java

Posted on 2002-07-05
11
16,957 Views
Last Modified: 2012-05-04
I require a login form created in java asking for a username and password. The password can either be hardcoded or coming from a text file.

If the user logins unsuccessfully it displays a msg and the user retries for 3 times after that the app closes.

If the user logins successfully it displays a new form displaying a label (You logged in successfully!) and a button to exit the app.


Iam using JCreator 2.5.

Now is there any code that i can look at to acheive this.
Iam a beginner in Java but have worked for 3 yrs in VB and Oracle/SQL Server.


Nomi.
0
Comment
Question by:Syed Irtaza Ali
11 Comments
 
LVL 6

Expert Comment

by:Marine
ID: 7132337
is this an application or the user will log in though a website ? Either task is easy to perform.
0
 

Expert Comment

by:tekel
ID: 7132649
I recommend using STRUTS http://jakarta.apache.org/struts/

down load the jar file.  the jar file contains a demo.  It's demo has a login page which does validation.

The big bonus is that you'll be using a very robust and stable framework.  Since your starting out in Java, you might as well start by writing good code.  STRUTS implements the MVC model.  

Sounds difficult but since you have years of programming experience you shouldn't have too much difficulty.

- tekel
0
 
LVL 1

Accepted Solution

by:
rahul_ashish earned 50 total points
ID: 7134723
/*this program is connecting to MySQL for the login verification. i think using Database is much secure than writing it to a file. use this code with modification

*/

import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
import java.sql.*;
import java.awt.event.*;

public class Login extends JFrame {
  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanel1 = new JPanel();
  JTextField jlogin = new JTextField(20);
  JPasswordField jpass = new JPasswordField(20);
  String[] config = new String[7];
  String[] profile = new String[2];
  private Connection  connection;
  private Statement stm;
  private ResultSet rsTemp;
  private MySQLConn mysql;

  /**
   * Constructs a new instance.
   */
  public Login(String[] config) {
    super();
    this.config=config;
    mysql=new MySQLConn(config);

    try  {
      connection=mysql.getConnection();
      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Initializes the state of this instance.
   */
  private void jbInit() throws Exception {
    Border border = new EtchedBorder();

    this.getContentPane().setLayout(borderLayout1);
    this.setSize(new Dimension(330, 160));
    this.setTitle("Login STARS");
    this.setResizable(false);
    jPanel1.setBorder(border);
    jPanel1.add(AddTextBox());
    this.getContentPane().add(jPanel1,BorderLayout.CENTER);

  }

  private JPanel AddTextBox(){
    JPanel panelcontainer=new JPanel();
    JPanel jPanelLogin=new JPanel();
    JPanel jPanelPass=new JPanel();
    JPanel jPanelButton=new JPanel();
    JButton jbuttonLogin= new JButton("Login");
    JButton jbuttonCancel = new JButton("Cancel");

    panelcontainer.setLayout(new VerticalFlowLayout());
    jPanelLogin.add(new JLabel("LoginId       "));
    jPanelLogin.add(jlogin);
    panelcontainer.add(jPanelLogin);
    jPanelPass.add(new JLabel("Password"));
    jPanelPass.add(jpass);
    panelcontainer.add(jPanelPass);
    jbuttonLogin=setAction(jbuttonLogin);
    jPanelButton.add(jbuttonLogin);
    jbuttonCancel=setAction(jbuttonCancel);
    jPanelButton.add(jbuttonCancel);
    panelcontainer.add(jPanelButton);
    panelcontainer.setBorder(new EtchedBorder());

    return panelcontainer;
  }

  private JButton setAction(JButton button){

    if((button.getText().trim()).equals("Login")){
      button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
          String query="Select * from login where userid='";

          try{
             int i=0
             boolean bLogin=false;
             //use a while loop here like
            while(i<3 && !bLogin){
            if((jlogin.getText().trim()).equals(""))
              JOptionPane.showMessageDialog(null,"Enter LoginId",
                "Error STARS",JOptionPane.ERROR_MESSAGE);
            else{
              stm = connection.createStatement();
              query = query + jlogin.getText().trim() + "'";
              rsTemp=stm.executeQuery(query);
              if(!rsTemp.next()){
                JOptionPane.showMessageDialog(null,"Invalid LoginId",
                          "Error STARS",JOptionPane.ERROR_MESSAGE);
                rsTemp.close();
                stm.close();
              }
              else
               do{
                  String pass=rsTemp.getString(3);
                  if(pass.equals(new String(jpass.getPassword()))){
                    profile[0]=Integer.toString(rsTemp.getInt(1));
                    profile[1]=rsTemp.getString(3).toString();
                    Stars.closeLoginFrame();
                    connection.close();
                    bLogin=true
                    }
                  else{
                    JOptionPane.showMessageDialog(null,"Invalid Password",
                       "Error STARS",JOptionPane.ERROR_MESSAGE);
                    rsTemp.close();
                    stm.close();
                  }
              } while(rsTemp.next());
            }
            i++;
           }//end of while
           if(i>2){
             System.exit(0);
           }else if(bLogin){
             //next action
           }
          }catch(Exception ex){
            ex.printStackTrace();
          }
        }
      });
    }
    else if((button.getText().trim()).equals("Cancel")){
      button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
          try{
            if(JOptionPane.showConfirmDialog(null,"Do you want to exit?",
                "Confirm STARS",JOptionPane.YES_NO_OPTION)==0){
              System.exit(0);
              connection.close();
            }

          }catch(Exception ex){
            ex.printStackTrace();
          }
        }
      });
    }


    return button;
  }

}
0
 
LVL 2

Author Comment

by:Syed Irtaza Ali
ID: 7136970
rahul i copied the code and pasted it. Got a few errors which were fixed easily except these

D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:17: cannot resolve symbol
symbol  : class MySQLConn  
location: class Login
 private MySQLConn mysql;
         ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:25: cannot resolve symbol
symbol  : class MySQLConn  
location: class Login
   mysql=new MySQLConn(config);
             ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:60: cannot resolve symbol
symbol  : class VerticalFlowLayout  
location: class Login
   panelcontainer.setLayout(new VerticalFlowLayout());
                                ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:108: cannot resolve symbol
symbol: variable Stars  
                   Stars.closeLoginFrame();
                   ^
4 errors


Please could u also send the code for the MySQL connection and other classes. I think they are missing.
0
 
LVL 2

Author Comment

by:Syed Irtaza Ali
ID: 7136981
rahul i copied the code and pasted it. Got a few errors which were fixed easily except these

D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:17: cannot resolve symbol
symbol  : class MySQLConn  
location: class Login
 private MySQLConn mysql;
         ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:25: cannot resolve symbol
symbol  : class MySQLConn  
location: class Login
   mysql=new MySQLConn(config);
             ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:60: cannot resolve symbol
symbol  : class VerticalFlowLayout  
location: class Login
   panelcontainer.setLayout(new VerticalFlowLayout());
                                ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:108: cannot resolve symbol
symbol: variable Stars  
                   Stars.closeLoginFrame();
                   ^
4 errors


Please could u also send the code for the MySQL connection and other classes. I think they are missing.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 2

Author Comment

by:Syed Irtaza Ali
ID: 7137069
rahul i copied the code and pasted it. Got a few errors which were fixed easily except these

D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:17: cannot resolve symbol
symbol  : class MySQLConn  
location: class Login
 private MySQLConn mysql;
         ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:25: cannot resolve symbol
symbol  : class MySQLConn  
location: class Login
   mysql=new MySQLConn(config);
             ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:60: cannot resolve symbol
symbol  : class VerticalFlowLayout  
location: class Login
   panelcontainer.setLayout(new VerticalFlowLayout());
                                ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:108: cannot resolve symbol
symbol: variable Stars  
                   Stars.closeLoginFrame();
                   ^
4 errors


Please could u also send the code for the MySQL connection and other classes. I think they are missing.
0
 
LVL 2

Author Comment

by:Syed Irtaza Ali
ID: 7137086
rahul i copied the code and pasted it. Got a few errors which were fixed easily except these

D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:17: cannot resolve symbol
symbol  : class MySQLConn  
location: class Login
 private MySQLConn mysql;
         ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:25: cannot resolve symbol
symbol  : class MySQLConn  
location: class Login
   mysql=new MySQLConn(config);
             ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:60: cannot resolve symbol
symbol  : class VerticalFlowLayout  
location: class Login
   panelcontainer.setLayout(new VerticalFlowLayout());
                                ^
D:\electric\JavaCodes\JavaPrograms\GetParam\Login.java:108: cannot resolve symbol
symbol: variable Stars  
                   Stars.closeLoginFrame();
                   ^
4 errors


Please could u also send the code for the MySQL connection and other classes. I think they are missing.
0
 
LVL 1

Expert Comment

by:rahul_ashish
ID: 7145322
these are the errors to connect to the MySQL database
in the linux machine for that u need a mysql driver

since u r storing ur password in a file or something, remove MySQL statemnents.

instead add the file access statement.
0
 
LVL 1

Expert Comment

by:rahul_ashish
ID: 7145326
for verticalflow layout take this codeimport java.awt.*;

/**
 * A vertical flow layout is used to lay out components in a panel.
 * It will arrange the components from top to bottom until no more components fit in the same column.
 * The columns can be aligned vertically.
 *
 * @version 1.0.2
 */
public class VerticalFlowLayout
    implements LayoutManager
{

    /**
     * The top alignment variable.
     */
    public static final int TOP = 1;

    /**
     * The centre alignment variable.
     */
    public static final int CENTER       = 0;

    /**
     * The bottom alignment variable.
     */
    public static final int BOTTOM = 2;
    /**
     * Vertical alignment left
     */
    public static final int LEFT = 3;
    /**
     * Vertical alignment right
     */
    public static final int RIGHT = 4;

    int align;
    int vAlign; // Tim added horizontal alignment
    int hgap;
    int vgap;
    boolean maximise;

    /**
     * Constructs a new layout with a centered alignment and a
     * default 5-unit horizontal and vertical gap.
     */
    public VerticalFlowLayout()
    {
        this(CENTER, 5, 5, false);
    }

    /**
     * Constructs a new layout with the specified alignment and a
     * default 5-unit horizontal and vertical gap.
     * @param align the alignment value
     */
    public VerticalFlowLayout(int align)
    {
        this(align, 5, 5, false);
    }

    /**
     * Constructs a new layout with the specified alignment and gap
     * values.
     * @param align the alignment value
     * @param hgap the horizontal gap variable
     * @param vgap the vertical gap variable
     */
    public VerticalFlowLayout(int align, int hgap, int vgap)
    {
        this(align, hgap, vgap, false);
    }

    /**
     * Constructs a new layout with the specified alignment and gap
     * values.
     * @param align the alignment value
     * @param hgap the horizontal gap variable
     * @param vgap the vertical gap variable
     */
    public VerticalFlowLayout(int align, int hgap, int vgap, boolean maximise)
    {
        if (align!=TOP && align!=CENTER && align!=BOTTOM)
            throw new IllegalArgumentException("illegal alignment value:"+align);
        if (hgap<0)
            throw new IllegalArgumentException("horizontal gap is less than 0");
        if (vgap<0)
            throw new IllegalArgumentException("vertical gap is less than 0");
        this.align = align;
        this.hgap = hgap;
        this.vgap = vgap;
        this.maximise = maximise;
    }

    /**
     * Returns the alignment value for this layout (TOP, CENTER, or BOTTOM).
     */
    public int getAlignment()
    {
        return align;
    }

    /**
     * Sets the alignment value for this layout.
     * @param align the alignment value (TOP, CENTER, or BOTTOM).
     */
    public void setAlignment(int align)
    {
        if (align!=TOP && align!=CENTER && align!=BOTTOM)
            throw new IllegalArgumentException("illegal alignment value:"+align);
        this.align = align;
    }
    /**
     * Set the verical alignment value.
     * @param aligns (LEFT, CENTER, or RIGHT)
     */
    public void setHorizontalAlignment(int align)
    {
        if (align!=LEFT && align!=RIGHT && align!=CENTER)
            throw new IllegalArgumentException("illegal alignment value:"+align);
        this.vAlign = align;
    }
    /**
     * Returns the horizontal gap between components.
     */
    public int getHgap()
    {
        return hgap;
    }

    /**
     * Sets the horizontal gap between components.
     * @param hgap the horizontal gap between components
     */
    public void setHgap(int hgap)
    {
        if (hgap<0)
            throw new IllegalArgumentException("horizontal gap is less than 0");
        this.hgap = hgap;
    }

    /**
     * Returns the vertical gap between components.
     */
    public int getVgap()
    {
        return vgap;
    }

    /**
     * Sets the vertical gap between components.
     * @param vgap the vertical gap between components
     */
    public void setVgap(int vgap)
    {
        if (vgap<0)
            throw new IllegalArgumentException("vertical gap is less than 0");
        this.vgap = vgap;
    }

    /**
     * Adds the specified component to the layout. Not used by this class.
     * @param name the name of the component
     * @param comp the the component to be added
     */
    public void addLayoutComponent(String name, Component comp)
    {}

    /**
     * Removes the specified component from the layout. Not used by this class.
     * @param comp the component to remove
     */
    public void removeLayoutComponent(Component comp) {
    }

    /**
     * Returns the preferred dimensions for this layout given the components
     * in the specified target container.
     * @param target the component which needs to be laid out
     * @see Container
     * @see #minimumLayoutSize
     */
    public Dimension preferredLayoutSize(Container target)
    {
        Dimension dim = new Dimension(0, 0);
        int nmembers = target.getComponentCount();
        for (int i=0; i<nmembers; i++)
        {
            Component m = target.getComponent(i);
            if (m.isVisible())
            {
                Dimension d = maximise ? m.getMaximumSize() : m.getPreferredSize();
                dim.width = Math.max(dim.width, d.width);
                if (i>1)
                    dim.height += vgap;
                dim.height += d.height;
            }
        }
        Insets insets = target.getInsets();
        dim.width += insets.left + insets.right + hgap*2;
        dim.height += insets.top + insets.bottom + vgap*2;
        return dim;
    }

    /**
     * Returns the minimum dimensions needed to layout the components
     * contained in the specified target container.
     * @param target the component which needs to be laid out
     * @see #preferredLayoutSize
     */
    public Dimension minimumLayoutSize(Container target)
    {
        Dimension dim = new Dimension(0, 0);
        int nmembers = target.getComponentCount();
        for (int i=0; i<nmembers; i++)
        {
            Component m = target.getComponent(i);
            if (m.isVisible())
            {
                Dimension d = m.getMinimumSize();
                dim.width = Math.max(dim.width, d.width);
                if (i>0)
                    dim.height += vgap;
                dim.height += d.height;
            }
        }
        Insets insets = target.getInsets();
        dim.width += insets.left + insets.right + hgap*2;
        dim.height += insets.top + insets.bottom + vgap*2;
        return dim;
    }

    /**
     * Centers the elements in the specified column, if there is any slack.
     * @param target the component which needs to be moved
     * @param x the x coordinate
     * @param y the y coordinate
     * @param width the width dimensions
     * @param height the height dimensions
     * @param columnStart the beginning of the column
     * @param columnEnd the the ending of the column
     */
    private void moveComponents(Container target, int x, int y, int width, int height, int columnStart, int columnEnd)
    {
        switch (align)
        {
          case TOP:
            break;
          case CENTER:
            y += height/2;
            break;
          case BOTTOM:
            y += height;
            break;
        }
        for (int i=columnStart; i<columnEnd; i++)
        {
            Component m = target.getComponent(i);
            Rectangle mbounds = m.getBounds();
            int X = x+(width-mbounds.width)/2; //center
            if (m.isVisible())
            {
                if (vAlign == LEFT)
                    X = x;
                else if (vAlign == RIGHT)
                    X = x+(width-mbounds.width);
                m.setLocation(X, y);
                y += vgap+mbounds.height;
            }
        }
    }

    /**
     * Lays out the container. This method will actually reshape the
     * components in the target in order to satisfy the constraints of
     * the BorderLayout object.
     * @param target the specified component being laid out.
     * @see Container
     */
    public void layoutContainer(Container target)
    {
        Insets insets = target.getInsets();
        Rectangle bounds = target.getBounds();
        int maxheight = bounds.height - (insets.top + insets.bottom + vgap*2);
        int nmembers = target.getComponentCount();
        int y = 0, x = insets.left + hgap;
        int rowv = 0, start = 0;

        for (int i=0; i<nmembers; i++)
        {
            Component m = target.getComponent(i);
            if (m.isVisible())
            {
                Dimension d = maximise ? m.getPreferredSize() : m.getPreferredSize();
                m.setSize(d.width, d.height);

                if ((y==0) || ((y+d.height) <= maxheight))
                {
                    if (y>0)
                        y += vgap;
                    y += d.height;
                    rowv = Math.max(rowv, d.width);
                }
                else
                {
                    moveComponents(target, x, insets.top+vgap, rowv, maxheight-y, start, i);
                    x += hgap+rowv;
                    y = d.height;
                    rowv = d.width;
                    start = i;
                }
            }
        }
        moveComponents(target, x, insets.top+vgap, rowv, maxheight-y, start, nmembers);
    }

    /**
     * Returns the string representation of this layout's values.
     */
    public String toString()
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append(getClass().getName());
        buffer.append("[hgap=");
        buffer.append(hgap);
        buffer.append(",vgap=");
        buffer.append(vgap);
        switch (align) {
          case TOP:
            buffer.append(",align=top");
            break;
          case CENTER:
            buffer.append(",align=center");
            break;
          case BOTTOM:
            buffer.append(",align=bottom");
            break;
        }
        buffer.append("]");
        return buffer.toString();
    }
}

0
 
LVL 2

Author Comment

by:Syed Irtaza Ali
ID: 7145805
rahul i have compiled the code successfully, now how do I run it.

I mean how do I use the Login constructor to open the Login form.


0
 
LVL 2

Author Comment

by:Syed Irtaza Ali
ID: 7148733
was having the problem running it using JCreator 2.5

but when ran from command prompt by supplying the ClassPath for tools.jar, it ran successfully. rahul can u explain y tools.jar was required in the classpath?
Also i noticed you did not add the

this.show();

line in the JPanel code to display the login form, is it that u missed it or are there other ways to display this form after the constructor is created?

Thanks.

Nomi.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
IT Company 5 69
parentbit challenge 3 52
word0 challenge 4 54
create a gui in perl 3 46
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now