When a component receives focus, ie, is the element of the screen that is active FocusEvent type events occur.
To make an object can listen to events FocusEvent FocusListener type must implement the interface, and it must be added as to the method FocusListener
public void addFocusListener(FocusListener fl)
The methods of this interface are:
public void focusGained(FocusEvent e)
public void foculsLost(FocusEvent e)
Given the existence of temporary changes in focus (for example when using scroll bars associated with a TextArea, Choice List or component) or permanent (when you use the “Tab” key to navigate between components interface), the method is useful below:
Method | Description |
isTemporary() | Determines whether the event focus change is temporary or permanent.
|
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Color;
import java.awt.Button;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class JavaExampleShowingInterface extends Frame
{
private Label LblPass;
private Label LblUsrNm;
private TextField TxtNm;
private TextField TxtPass;
JavaExampleShowingInterface(String TTL)
{
setTitle(TTL);
setLayout(new GridLayout(3,3));
setSize(new Dimension(550,200));
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ee)
{
System.exit(0);
}
});
TxtNm=new TextField(30);
TxtNm.addFocusListener(new FocusList());
add(new Label("Your Name:"));
add(TxtNm);
LblPass=new Label();
add(LblPass);
TxtPass=new TextField(30);
TxtPass.setEchoChar('*');
TxtPass.addFocusListener(new FocusList());
add(new Label("Password Plz:"));
add(TxtPass);
LblPass=new Label();
add(LblPass);
add(new Button("OK"));
setVisible(true);
validate();
}
class FocusList implements FocusListener
{
public void focusGained(FocusEvent ee){}
public void focusLost(FocusEvent ee)
{
TextField Txt=(TextField)ee.getSource();
if(Txt.getText().equals("") && Txt==TxtNm)
{
LblUsrNm.setForeground(Color.RED);
LblUsrNm.setText("User name can not be blank.");
}
else
LblUsrNm.setText("");
if(Txt.getText().equals("") && Txt==TxtPass)
{
LblPass.setForeground(Color.RED);
LblPass.setText("Password can not be blank.");
}
else
LblPass.setText("");
}
}
public static void main(String[] aa)
{
new JavaExampleShowingInterface("Focus Listener In Java");
}
}