ADS

Using Focuslistener On Awt Textfield

The following example illustrates using FocusListener with AWT TextField.
 import java.awt.*;
import java.awt.event.*;
class TextFieldFocusEvent extends Frame implements FocusListener
{
TextField t1,t2;

    public TextFieldFocusEvent()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("FocusListener for TextField");
        setLayout(new FlowLayout());
       
        // Create 2 textfields
        t1=new TextField(20);
        t2=new TextField(20);
       
        // Add them
        add(t1);
        add(t2);
       
        // Add FocusListeners
        t1.addFocusListener(this);
        t2.addFocusListener(this);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public void focusGained(FocusEvent fe)
    {
        // Get what textfield got focus
        TextField t=(TextField)fe.getSource();
        t.setBackground(Color.LIGHT_GRAY);
    }
   
    public void focusLost(FocusEvent fe)
    {
        // Get what textfield lost focus
        TextField t=(TextField)fe.getSource();
        t.setBackground(Color.WHITE);
    }
   
    public static void main(String args[])
    {
        new TextFieldFocusEvent();
    }
}

focusGained() is called when a component gets focus i.e. when it is selected or active. You'll understand it in practical. focusLost() is called when a component loses its focus. Here focused field gets light gray background and non-focused gets white background.

TextFieldFocusEvent(): The code illustrating the FocusListener on AWT TextField is invoked here.

 The following example illustrates using FocusListener with AWT TextField Using FocusListener on AWT TextField

Next: Using FocusListener on AWT Button
Previous: Using WindowListener for AWT Frame

Subscribe to receive free email updates:

ADS