Java FocusAdapter handle focus event

Description

Java FocusAdapter handle focus event

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

import javax.swing.JButton;
import javax.swing.JFrame;

class MyFocusListener extends FocusAdapter {
   public void focusGained(FocusEvent evt) {
      System.out.println("The component gained the focus");
      System.out.println(evt);/*from   w  ww .  j a va  2s.  c o m*/
   }

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

public class Main {
   public static void main(String args[]) {
      JFrame frame = new JFrame("java2s.com");
      JButton component = new JButton();
      component.addFocusListener(new MyFocusListener());
      
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.add(component, BorderLayout.NORTH);
      frame.add(new JButton(), BorderLayout.NORTH);
      
      frame.setSize(640, 300);
      frame.setVisible(true);
   }
}



PreviousNext

Related