Handling Focus Changes : Focus « Swing JFC « Java

Handling Focus Changes


import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

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

public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addFocusListener(new MyFocusListener());
    JFrame f = new JFrame();

    f.setSize(300, 300);


class MyFocusListener extends FocusAdapter {
  public void focusGained(FocusEvent evt) {
    System.out.println("component gained the focus");

  public void focusLost(FocusEvent evt) {
    System.out.println("component lost the focus");


Related examples in the same category

1.Focus Cycle SampleFocus Cycle Sample
2.Button FocusButton Focus
3.Focus Traversal ExampleFocus Traversal Example
4.Focus ExampleFocus Example
5.Focus Concepts DemoFocus Concepts Demo
6.Track Focus Demo
7.Focus Traversal DemoFocus Traversal Demo
8.Use this method to determine whether a particular component has the focus
9.Requests focus for a component
10.Requests focus unless the component already has focus