1

Hi, This will show you how to create a login form using swing.

Please be aware that this form does not connect to anything.
( eg. A URL or a database)


This is just a little advanced example of one of the many things you can do in swing.

A working example of this script can be downloaded at:
http://programmers-paradise.net/forum/viewtopic.php?t=9

And Yes before I start getting attacked with accusations of deprecated values I am aware of one in this code.

:rolleyes:

Edited by peter_budo: Correcting colours in the post

/****************************************************************/
/*                          login	                            */
/*               Copyright 2006 Billy Anderson                  */
/****************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class login extends JFrame
{
	// Variables declaration
	private JLabel jLabel1;
	private JLabel jLabel2;
	private JTextField jTextField1;
	private JPasswordField jPasswordField1;
	private JButton jButton1;
	private JPanel contentPane;
	// End of variables declaration


	public login()
	{
		super();
		create();
		this.setVisible(true);
	}

	
	private void create()
	{
		jLabel1 = new JLabel();
		jLabel2 = new JLabel();
		jTextField1 = new JTextField();
		jPasswordField1 = new JPasswordField();
		jButton1 = new JButton();
		contentPane = (JPanel)this.getContentPane();

		//
		// jLabel1
		//
		jLabel1.setHorizontalAlignment(SwingConstants.LEFT);
		jLabel1.setForeground(new Color(0, 0, 255));
		jLabel1.setText("username:");
		//
		// jLabel2
		//
		jLabel2.setHorizontalAlignment(SwingConstants.LEFT);
		jLabel2.setForeground(new Color(0, 0, 255));
		jLabel2.setText("password:");
		//
		// jTextField1
		//
		jTextField1.setForeground(new Color(0, 0, 255));
		jTextField1.setSelectedTextColor(new Color(0, 0, 255));
		jTextField1.setToolTipText("Enter your username");
		jTextField1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				jTextField1_actionPerformed(e);
			}

		});
		//
		// jPasswordField1
		//
		jPasswordField1.setForeground(new Color(0, 0, 255));
		jPasswordField1.setToolTipText("Enter your password");
		jPasswordField1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				jPasswordField1_actionPerformed(e);
			}

		});
		//
		// jButton1
		//
		jButton1.setBackground(new Color(204, 204, 204));
		jButton1.setForeground(new Color(0, 0, 255));
		jButton1.setText("Login");
		jButton1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				jButton1_actionPerformed(e);
			}

		});
		//
		// contentPane
		//
		contentPane.setLayout(null);
		contentPane.setBorder(BorderFactory.createEtchedBorder());
		contentPane.setBackground(new Color(204, 204, 204));
		addComponent(contentPane, jLabel1, 5,10,106,18);
		addComponent(contentPane, jLabel2, 5,47,97,18);
		addComponent(contentPane, jTextField1, 110,10,183,22);
		addComponent(contentPane, jPasswordField1, 110,45,183,22);
		addComponent(contentPane, jButton1, 150,75,83,28);
		//
		// login
		//
		this.setTitle("Login To Members Area");
		this.setLocation(new Point(76, 182));
		this.setSize(new Dimension(335, 141));
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		this.setResizable(false);
	}

	/** Add Component Without a Layout Manager (Absolute Positioning) */
	private void addComponent(Container container,Component c,int x,int y,int width,int height)
	{
		c.setBounds(x,y,width,height);
		container.add(c);
	}

	
	private void jTextField1_actionPerformed(ActionEvent e)
	{
		

	}

	private void jPasswordField1_actionPerformed(ActionEvent e)
	{
		
	}

	private void jButton1_actionPerformed(ActionEvent e)
	{
		System.out.println("\njButton1_actionPerformed(ActionEvent e) called.");
		String username = new String(jTextField1.getText());
		String password = new String(jPasswordField1.getText());
		
		if(username.equals("") || password.equals("")) // If password and username is empty > Do this >>>
				{
					jButton1.setEnabled(false);
				JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>You must enter a username and password to login.</FONT></HTML>");	
				JOptionPane.showMessageDialog(null,errorFields); 
				jTextField1.setText("");
	   		    jPasswordField1.setText("");
	   		    jButton1.setEnabled(true);
				this.setVisible(true);
				}
				else
				{
		JLabel optionLabel = new JLabel("<HTML><FONT COLOR = Blue>You entered</FONT><FONT COLOR = RED> <B>"+username+"</B></FONT> <FONT COLOR = Blue>as your username.<BR> Is this correct?</FONT></HTML>");
int confirm =JOptionPane.showConfirmDialog(null,optionLabel);
switch(confirm){       // Switch > Case
	   	case JOptionPane.YES_OPTION:  // Attempt to Login user
	   	jButton1.setEnabled(false);   // Set button enable to false to prevent 2 login attempts
	   	break;

            case JOptionPane.NO_OPTION:   // No Case.(Go back. Set text to 0)
	   		jButton1.setEnabled(false);
	   		jTextField1.setText("");
	   		jPasswordField1.setText("");
	   		jButton1.setEnabled(true);
            break;
	   		
	   		case JOptionPane.CANCEL_OPTION:  // Cancel Case.(Go back. Set text to 0)
	   	    jButton1.setEnabled(false);
	   	    jTextField1.setText("");
	   	    jPasswordField1.setText("");
	   	    jButton1.setEnabled(true);
	   	    break;
	   	
	   	}   // End Switch > Case
	   	   
	  
	   }
	   }
		


	



	public static void main(String[] args)
	{
		JFrame.setDefaultLookAndFeelDecorated(true);
		JDialog.setDefaultLookAndFeelDecorated(true);
		try
		{
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		}
		catch (Exception ex)
		{
			System.out.println("Failed loading L&F: ");
			System.out.println(ex);
		}
		new login();
	};



}
8
Contributors
8
Replies
55
Views
10 Years
Discussion Span
Last Post by masijade
0

hi this is great please cud u help me out here ...
i did mine entirely before i saw urs but the thin is that when i trying to login nothing happends after
javackin appleviewer Login.java
it cums up but if i login with a user name and password its does not perfom any action i dont know why please it is very important that u help me..
here is the code snipet.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
/*
<applet code="Login.class" height=300 width=300>
</applet>
*/
public class Login extends JApplet implements ActionListener
{
/*D V*/
JPanel panel;
JFrame frame;
JLabel lo;
JLabel bo;
JLabel so;
JLabel title,title2;
JTextField bu;
JPasswordField wu;
JButton l;
JButton c;
JButton w;
GridBagLayout g;
GridBagConstraints gbc;
public void init()
{
/*I L V*/
g=new GridBagLayout();
gbc=new GridBagConstraints();
panel=(JPanel)getContentPane();
panel.setLayout(g);
/*A C P*/
lo=new JLabel("Login ID:");
gbc.ipady=2;
gbc.ipadx=2;
gbc.gridx=0;
gbc.gridy=4;
g.setConstraints(lo, gbc);
panel.add(lo);
lo.setForeground(Color.red);
lo.setBackground(Color.yellow);
panel.setBackground(Color.yellow);
bu=new JTextField(15);
gbc.ipady=2;
gbc.ipadx=2;
gbc.gridx=1;
gbc.gridy=4;
g.setConstraints(bu, gbc);
panel.add(bu);
/*A C P*/
bo=new JLabel("Password:");
bo.setForeground(Color.red);
gbc.ipady=2;
gbc.ipadx=2;
gbc.gridx=0;
gbc.gridy=5;
g.setConstraints(bo, gbc);
panel.add(bo);
wu=new JPasswordField(15);
gbc.ipady=2;
gbc.ipadx=2;
gbc.gridx=1;
gbc.gridy=5;
g.setConstraints(wu, gbc);
panel.add(wu);



/*A C P*/
w=new JButton("Cancel");
gbc.ipady=2;
gbc.ipadx=2;
gbc.gridx=1;
gbc.gridy=6;
g.setConstraints(w, gbc);
panel.add(w);
/*A C P*/
l=new JButton("Exit");
gbc.ipady=2;
gbc.ipadx=2;
gbc.gridx=2;
gbc.gridy=6;
g.setConstraints(l, gbc);
panel.add(l);
/*A C P*/
so=new JLabel("Music On Web");
so.setBackground(Color.yellow);
gbc.gridx=1;
gbc.gridy=0;
g.setConstraints(so, gbc);
panel.add(so);
/*A C P*/
c=new JButton("Login");
gbc.ipady=2;
gbc.ipadx=2;
gbc.gridx=0;
gbc.gridy=6;
g.setConstraints(c, gbc);
panel.add(c);
c.addActionListener(this);
l.addActionListener(this);
w.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand() == "Exit")
System.exit(0);
Object o=ae.getSource();
if(o==w)
{
bu.setText("");
wu.setText("");
}
if(o==c)
{
String tu=bu.getText();
if(tu.length()==0){
JOptionPane.showMessageDialog(this,new
String("LoginID can't be blank"));}
}
if(o==c)
{
String tu=wu.getText();
if(tu.length()==0){
JOptionPane.showMessageDialog(this,new
String("Enter ur password"));
return;}
}
if(c==o)
{
String s="name:   "  +bu.getText()+  "   password:    "   +wu.getText();
try
{
RandomAccessFile lFile=new RandomAccessFile("log.txt","rw");
lFile.seek(lFile.length());
lFile.writeBytes(s);
}  catch(IOException ie)
{
showStatus("unable to write" +ie);
}
if(c==o)
{
The myadd = new The();


/*start changes*/
myadd.init();
myadd.start();


int compCount = panel.getComponentCount();
java.util.Vector componentList = new java.util.Vector();
for(int i = 0; i < compCount; i++)
{
Component c = panel.getComponent(i);
componentList.addElement(c);
}


for(int i = 0; i < componentList.size(); i++)
{
Component c = (Component)componentList.elementAt(i);
panel.remove(c);
}


panel.add(myadd);


//use this method for thread safety
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run() {
javax.swing.SwingUtilities.updateComponentTreeUI(Login.this);
}
});
/*end changes*/
}
}
}
}

Edited by happygeek: fixed formatting

0

thanks for this informative posting. its really useful for me. this forum contain very useful information. i like it very much.

-1

nice.i got the output for that aftr correctin some mistakes comparing urs.........i d like to have codes for some other standard applications like applets.....etc.so wer can i get it. or else can u post tht here....pls .i m fond on getting the codes from ur site....

0

Thread Closed as it is old and has now become a simple dumping spot for "Give me teh codez" responses. No, thank you.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.