Focus events occur when a component gains or loses keyboard focus. Objects representing focus events are created from FocusEvent Class. The corresponding listener interface for FocusEvent Class is FocusListener interface. Each listener for FocusEvent should implement the FocusListener interface.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class FocusListenerExample extends JFrame implements FocusListener
{
JTextField txtUserid ;
JPasswordField txtpassword;
FocusListenerExample()
{
JPanel panel1 = new JPanel();
panel1.add(new JLabel("Enter Userid :"));
txtUserid = new JTextField(20);
panel1.add(txtUserid);
add(panel1,"North");
JPanel panel2 = new JPanel();
panel2.add(new JLabel("Enter Password:"));
txtpassword = new JPasswordField(20);
panel2.add(txtpassword);
add(panel2);
txtUserid.addFocusListener(this);
txtpassword.addFocusListener(this);
}
public void focusGained(FocusEvent e)
{
Component c= (Component)e.getSource();
Color green = new Color(0,200,0);
c.setBackground(green);
}
public void focusLost(FocusEvent e)
{
Component c= (Component)e.getSource();
Color white = new Color(255,255,255);
c.setBackground(white);
}
}
class FocusListenerJavaExample
{
public static void main(String[] args)
{
FocusListenerExample frame = new FocusListenerExample();
frame.setTitle("FocusListener Java Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100,200,400,200);
frame.setVisible(true);
}
}