How to Write a Focus Listener : FocusListener « Swing Event « Java Tutorial

Focus events are fired whenever a component gains or loses the keyboard focus.

How to Write a Focus Listener
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class UsingFocusListener {

  public static void main(String[] a) {
    JFrame frame = new JFrame();

    JTextField textField = new JTextField("A TextField");
    textField.addFocusListener(new FocusListener() {
      public void focusGained(FocusEvent e) {
        displayMessage("Focus gained", e);

      public void focusLost(FocusEvent e) {
        displayMessage("Focus lost", e);

      void displayMessage(String prefix, FocusEvent e) {
            + (e.isTemporary() ? " (temporary):" : ":")
            + e.getComponent().getClass().getName()
            + "; Opposite component: "
            + (e.getOppositeComponent() != null ? e.getOppositeComponent().getClass().getName()
                : "null"));


    frame.add(new JTextField(),"South");
    frame.setSize(300, 200);


15.16.1.The FocusListener Interface: respond to a component gaining or losing the focus
15.16.2.The event IDs defined in the FocusEvent class
15.16.3.How to Write a Focus ListenerHow to Write a Focus Listener
15.16.4.FocusListener and FocusEvent
15.16.5.Validating a JTextField When Permanently Losing the Focus
15.16.6.Use Focus Events in Swing
15.16.7.Validate a value on the lostFocus event