Java Swing Tutorial - Java FocusEvent FOCUS_FIRST








Syntax

FocusEvent.FOCUS_FIRST has the following syntax.

public static final int FOCUS_FIRST

Example

In the following code shows how to use FocusEvent.FOCUS_FIRST field.

/* w  w w .  ja  va 2  s  .c  om*/

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

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

public class Main {

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

    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) {
        System.out.println(e.getID() == FocusEvent.FOCUS_FIRST);
      }
    });
    frame.add(textField,"North");
    frame.add(new JTextField(),"South");
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}