Focus Listener

focusGained
focusLost

Applet : When user enter Password in TextField, if it is less that 8 characters long, display a Dialog “Invalid Password” otherwise display the password in TextArea.







import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class FrameMouseFocus extends Applet implements FocusListener,ActionListener
{
    Frame f;
    TextArea ta1;
    TextField tf1;
    Dialog d1;
    Button b1;
    Label l1;

    public void init()
    {
        f = new Frame();
        ta1=new TextArea(10,15);
        tf1=new TextField(10);
        l1 = new Label("Enter Password : ");
           
        add(l1);
        add(tf1);
        add(ta1);
        tf1.requestFocus();

        tf1.setEchoChar('*');
        tf1.addFocusListener(this);
    }
    public void focusLost(FocusEvent f1)
    {
        if(tf1.getText().length() < 8)
        {
            d1 = new Dialog(f,"Invalid Password");
            b1 = new Button("OK");
            d1.setSize(150,100);
            d1.setVisible(true);
            d1.add(b1);
            b1.addActionListener(this);
            tf1.setText("");
        }
        else
        {
            ta1.append(tf1.getText()+"\n");
            tf1.setText("");
            tf1.requestFocus();
        }
    }
    public void actionPerformed(ActionEvent a)
    {
        if(a.getSource() == b1)
        {
            d1.setVisible(false);
            tf1.requestFocus();
        }
    }
    public void focusGained(FocusEvent f)
    {
       
    }
}

Click new -> File -> html    and save this file as FrameMouseFocus.html

<BODY>

<Applet code=FrameMouseFocus.class height=200 width=400 >

</Applet>

</BODY>