What is the importance of a FocusListener interface in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

FocusListener

  • The focus events are generated whenever a component gains or loses the keyboard focus.
  • The Objects representing focus events are created from FocusEvent Class.
  • The corresponding listener interface for FocusEvent class is a FocusListener interface. Each listener for FocusEvent can implement the FocusListener interface.
  • The FocusListener interface contains two methods focusGained(): Called by the AWT just after the listened-to component gets the focus and focusLost(): Called by the AWT just after the listened-to component loses the focus.

Syntax

public interface FocusListener extends EventListener {
   public void focusGained(FocusEvent fe);
   public void focusLost(FocusEvent fe);

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FocusListenerTest extends JPanel implements FocusListener {
   private JTextField textField;
   public FocusListenerTest() {
      setLayout(new BorderLayout());
      textField = new JTextField();
      textField.addFocusListener(this);
      add(textField, BorderLayout.NORTH);
   }
   public void focusGained(FocusEvent fe) {
      System.out.println("Text field gained focus");
   }
   public void focusLost(FocusEvent fe) {
      System.out.println("Text field lost focus");
   }
   public static void main(String args[]) {
      JFrame frame = new JFrame();
      frame.add(new FocusListenerTest());
      frame.setTitle("FocusListener Test");
      frame.setSize(375, 250);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}

 

Output

 

 

 

raja
Published on 19-Jul-2019 16:29:51
Advertisements