awt

Focus listener example

This is an example that discusses how to use FocusListener in Java. This is a very handy feature when you have several components and you want to monitor and handle the event when on of them gains or looses focus.

In short, all you have to do in order to work with a FocusListener is:

  • Create a new FocusListener
  • Override the methods that correspond to the events that you want to monitor about the component e.g focusGainedfocusLost and customize as you wish the handling of the respective events. Now every time the monitored component gains or looses focus the corresponding method will be executed.
  • Use the addFocusListener method of the component you want to monitor, in order to add the FocusListener you’ve created.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class FocusListener {

  public static void main(String[] args) {

// Create frame with specific title

Frame frame = new Frame("Example Frame");

// Create a component to add to the frame; in this case a text area with sample text

Component textArea = new TextArea("Sample text...");

// Create a component to add to the frame; in this case a button

Component button = new Button("Click Me!!");

// Add the components to the frame; by default, the frame has a border layout

frame.add(textArea, BorderLayout.NORTH);

frame.add(button, BorderLayout.SOUTH);

// Add a focus listener to the button component

button.addFocusListener(new FocusListener() {

    @Override

    public void focusLost(FocusEvent e) {

  if (e.isTemporary()) {

// The component will gain the focus when its window becomes active again

System.out.println("Button lost focus temporary");

  } else {

// The focus moves to another component in the same window

System.out.println("Button lost focus permanently");

  }

  // The component that gained the focus

  Component c = e.getOppositeComponent();

  System.out.println("Componenet " + c + " gained focus");

    }

    @Override

    public void focusGained(FocusEvent e) {

  // The component that lost the focus

  Component c = e.getOppositeComponent();

  System.out.println("Componenet " + c + " lost focus");

    }

});

// Show the frame

int width = 300;

int height = 300;

frame.setSize(width, height);

frame.setVisible(true);
  }

}

 
This was an example on how to work with FocusListener in a Java Desktop Application.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button