Java
Slip17
Q.1) Write a Java program to design a screen using Awt that will take a user name and password. If the user name and password are not same, raise an Exception with appropriate message. User can have 3 login chances only. Use clear button to clear the TextFields. [Marks 30]
Solution
import java.awt.event.*;
import javax.swing.*;
public class Assgn17 extends Frame implements ActionListener
{
Label name, pass;
TextField nameText;
TextField passText;
Button login, end;
static int attempt=0;
public Assgn17()
{
name = new Label(" Name:");
pass = new Label("Password:");
nameText = new TextField(20);
passText = new TextField(20);
passText.setEchoChar('*');
login = new Button("Login");
end = new Button("End");
login.addActionListener(this);
end.addActionListener(this);
setLayout(new FlowLayout());
add(name);
add(nameText);
add(pass);
add(passText);
add(login);
add(end);
setTitle("Login Check");
setSize(300,300);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
Button btn = (Button)ae.getSource();
if(btn == end)
{
System.exit(0);
}
if(btn == login)
{
try
{
String user = nameText.getText();
String pass = new String(passText.getText());
if(user.compareTo(pass)==0)
{
JOptionPane.showMessageDialog(null,"Login Successful");
System.exit(0);
//new Mouse();
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e)
{
attempt++;
JOptionPane.showMessageDialog(null,"Login Failed");
nameText.setText("");
passText.setText("");
nameText.requestFocus();
if(attempt == 3)
{
JOptionPane.showMessageDialog(null,"3 Attempts Over","Login",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}//if
}//catch
}//login
}//action
public static void main(String args[])
{
new Assgn17();
}
}
Tags:
java