Java AWT KeyboardFocusManager handle property change event

Description

Java AWT KeyboardFocusManager handle property change event

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main extends JPanel {
   JTextField t1, f2, f3, f4, f5, f6;

   public Main() {
      super(new BorderLayout());

      JPanel mugshots = new JPanel(new GridLayout(2, 3));
      t1 = new JTextField(10);
      t1.setName("1");
      mugshots.add(t1);/*w w w .j a va  2 s.  c  o m*/
      f2 = new JTextField(10);
      f2.setName("2");
      mugshots.add(f2);
      f3 = new JTextField(10);
      f3.setName("3");
      mugshots.add(f3);
      f4 = new JTextField(10);
      f4.setName("4");
      mugshots.add(f4);
      f5 = new JTextField(10);
      f5.setName("5");
      mugshots.add(f5);
      f6 = new JTextField(10);
      f6.setName("6");
      mugshots.add(f6);

      setPreferredSize(new Dimension(450, 350));
      add(mugshots, BorderLayout.CENTER);
      setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

      KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
      focusManager.addPropertyChangeListener(new PropertyChangeListener() {
         public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();
            if (("focusOwner".equals(prop)) && ((e.getNewValue()) instanceof JTextField)) {
               Component comp = (Component) e.getNewValue();
               String name = comp.getName();
               System.out.println(name);
            }
         }
      });
   }

   public static void main(String[] args) {
      JFrame frame = new JFrame("TrackFocusDemo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JComponent newContentPane = new Main();
      newContentPane.setOpaque(true); // content panes must be opaque
      frame.setContentPane(newContentPane);

      frame.pack();
      frame.setVisible(true);
   }
}



PreviousNext

Related