FocusListener in Java


In this article, we discuss how to implement FocusListener in Java. The Netbeans IDE is used for the development of the example.

What is FocusListener

FocusListener is basically an interface that for receiving Keyboard focus events on components.

Methods Inside focusListener

  • void focusGained(FocusEvent e)

         This method is called when the component gains the keyboard focus.

  • void focusLost(FocusEvent e)

         This method is called when the component losses the keyboard focus.

Packages Imported


This package is imported to provide a graphical user interface for programs, it is an extended version of AWT. The component of Swing are JFrmae, JLABEL, JScrollPane and so on.


AWT stands for Abstract Window Toolkit, this package is imported to use components of AWT, like label, list, combobox and so on.


This package is imported to handle the various action events.


In this example; we implement a Focus Listener in Java using the Netbeans IDE. There are certain steps in the Netbeans IDE that we need to follow as explained below.

Step 1

Open the Netbeans IDE


Step 2

Click on "File" from the Menu bar as in the following:


Step 3

Click on "New Project" as in the following:


Step 4

Select "Java" and "Java application" then click on "Next" as in the following:


Step 5

Instead of project name specify "FocusListenerDemo" and instead of main class also specify "FocusListenerDemo" and click on "Finish".


Step 6

In this class write the following code (the class name is "FocusListenrDemo"):

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

public class FocusEventDemo implements FocusListener


 JTextArea ta;

 public static void main(String[] args)


  EventQueue.invokeLater(new Runnable()



   public void run()


    new FocusEventDemo().BuildGUI();        




 public void BuildGUI()


   JFrame f = new JFrame();      


   f.setTitle("Creating a Table Example");



   JPanel gc = new JPanel();       

   JButton btn = new JButton("Example Button");

   btn.setActionCommand("Example Button");


   String[] items = {"London", "Paris", "Madrid", "Moscow", "Wellington"};

   JComboBox cmb = new JComboBox(items);


   JLabel lbl = new JLabel("Graphical Components:");       

   JTextField tf = new JTextField("A Text Field");


   ta = new JTextArea("Event Feedback..");


   JScrollPane st = new JScrollPane(ta);      






   f.add(st, BorderLayout.CENTER);       




   public void focusGained(FocusEvent e) {

   ta.append(e.getComponent().getClass().getName() + " has got the focus\n");



  public void focusLost(FocusEvent e) {

  ta.append(e.getComponent().getClass().getName() + " has lost the focus\n");






Step 7


Now go to "" and right-click on that, click on "Run" from the menu bar as in the following:






The output shows that java.swing,JComboBox has gotten the focus.




Similar Articles