Java Swing Tutorial - Java FocusListener .focusGained (FocusEvent e)








Syntax

FocusListener.focusGained(FocusEvent e) has the following syntax.

void focusGained(FocusEvent e)

Example

In the following code shows how to use FocusListener.focusGained(FocusEvent e) method.

/*w ww.j  a va 2  s.  c  om*/

import java.awt.Dimension;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class Main extends JPanel implements FocusListener {
  public Main() {
    JTextField textField = new JTextField("A TextField");
    textField.addFocusListener(this);
    JLabel label = new JLabel("A Label");
    label.addFocusListener(this);
    add(label);

    String comboPrefix = "Item #";
    final int numItems = 15;
    Vector vector = new Vector(numItems);
    for (int i = 0; i < numItems; i++) {
      vector.addElement(comboPrefix + i);
    }
    JComboBox comboBox = new JComboBox(vector);
    comboBox.addFocusListener(this);
    add(comboBox);

    JButton button = new JButton("A Button");
    button.addFocusListener(this);
    add(button);

    JList list = new JList(vector);
    list.setSelectedIndex(1);
    list.addFocusListener(this);
    JScrollPane listScrollPane = new JScrollPane(list);

    listScrollPane.getVerticalScrollBar().setFocusable(false);
    listScrollPane.getHorizontalScrollBar().setFocusable(false);
    add(listScrollPane);

    setPreferredSize(new Dimension(450, 450));
  }

  void displayMessage(String prefix, FocusEvent e) {
    System.out.println(prefix
        + (e.isTemporary() ? " (temporary):" : ":")
        + e.getComponent().getClass().getName()
        + "; Opposite component: "
        + (e.getOppositeComponent() != null ? e.getOppositeComponent().getClass().getName()
            : "null"));
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("FocusEventDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JComponent newContentPane = new Main();
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);

  }

  public void focusGained(FocusEvent e) {
    displayMessage("Focus gained", e);
  }

  public void focusLost(FocusEvent e) {
    displayMessage("Focus lost", e);
  }
}