Java AWT FocusEvent get opposite focus component

Description

Java AWT FocusEvent get opposite focus component

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

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

public class Main {
  public static void main(String[] argv) throws Exception {
    JButton component = new JButton("a");
    component.addFocusListener(new MyFocusListener());

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(component);/*from w w w.  jav a  2s. c  om*/
    f.pack();
    f.setVisible(true);

  }
}

class MyFocusListener extends FocusAdapter {
  public void focusGained(FocusEvent evt) {

    Component c = evt.getOppositeComponent();
    System.out.println(c.getName());
  }

  public void focusLost(FocusEvent evt) {

    Component c = evt.getOppositeComponent();
    System.out.println(c.getName() + "Opposite Component");
  }
}  



PreviousNext

Related