Java Tutorial/Swing Event/Focus

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Changes the focus traversal keys for the entire application.

   <source lang="java">

import java.awt.AWTKeyStroke; import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(KeyboardFocusManager
       .getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(
           KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
   set.add(KeyStroke.getKeyStroke("F2"));
   KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(
       KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
 }

}</source>





Change the backward focus traversal keys for the application

   <source lang="java">

import java.awt.AWTKeyStroke; import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(KeyboardFocusManager
       .getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(
           KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
   set.add(KeyStroke.getKeyStroke("F3"));
   KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(
       KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set);
 }

}</source>





Change the forward focus traversal keys for a component

   <source lang="java">

import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.JButton; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton("a");
   Set set = new HashSet(component
       .getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
   set.add(KeyStroke.getKeyStroke("F2"));
   component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
 }

}</source>





Determining If a Focus Lost Is Temporary or Permanent

   <source lang="java">

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.add(component);
   f.pack();
   f.setVisible(true);
   
   
 }

} class MyFocusListener extends FocusAdapter {

 public void focusGained(FocusEvent evt) {
   System.out.println("gained the focus.");
 }
 public void focusLost(FocusEvent evt) {
   System.out.println("lost the focus.");
   boolean isTemporary = evt.isTemporary();
 }

}</source>





Determining the Opposite Component of a Focus Event

   <source lang="java">

import java.awt.ruponent; 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.add(component);
   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");
 }

}</source>





Finding the Next Focusable Component

   <source lang="java">

import java.awt.ruponent; import java.awt.Container; import java.awt.FlowLayout; import java.awt.FocusTraversalPolicy; import java.awt.KeyboardFocusManager; import javax.swing.JButton; import javax.swing.JFrame; public class Main {

 public static void main(String[] argv) {
   JFrame frame = new JFrame();
   JButton component1 = new JButton("1");
   JButton component2 = new JButton("2");
   JButton component3 = new JButton("3");
   frame.setLayout(new FlowLayout());
   frame.add(component1);
   frame.add(component2);
   frame.add(component3);
   frame.pack();
   frame.setVisible(true);
   System.out.println(findNextFocus().getName());
 }
 public static Component findNextFocus() {
   Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
   Container root = c.getFocusCycleRootAncestor();
   FocusTraversalPolicy policy = root.getFocusTraversalPolicy();
   Component nextFocus = policy.getComponentAfter(root, c);
   if (nextFocus == null) {
     nextFocus = policy.getDefaultComponent(root);
   }
   return nextFocus;
 }

}</source>





Find the previous focusable component

   <source lang="java">

import java.awt.ruponent; import java.awt.Container; import java.awt.FlowLayout; import java.awt.FocusTraversalPolicy; import java.awt.KeyboardFocusManager; import javax.swing.JButton; import javax.swing.JFrame; public class Main {

 public static void main(String[] argv) {
   JFrame frame = new JFrame();
   JButton component1 = new JButton("1");
   JButton component2 = new JButton("2");
   JButton component3 = new JButton("3");
   frame.setLayout(new FlowLayout());
   frame.add(component1);
   frame.add(component2);
   frame.add(component3);
   frame.pack();
   frame.setVisible(true);
   System.out.println(findPrevFocus().getName());
 }
 public static Component findPrevFocus() {
   Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
   Container root = c.getFocusCycleRootAncestor();
   FocusTraversalPolicy policy = root.getFocusTraversalPolicy();
   Component prevFocus = policy.getComponentBefore(root, c);
   if (prevFocus == null) {
     prevFocus = policy.getDefaultComponent(root);
   }
   return prevFocus;
 }

}</source>





Focus auto-setting

   <source lang="java">

import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; public class ButtonFocus {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Focus Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JButton focusButton = new JButton("Focused");
   JButton notFocusButton = new JButton("Not Focused");
   frame.setLayout(new FlowLayout());
   frame.add(focusButton);
   frame.add(notFocusButton);
   frame.setSize(300, 100);
   frame.setVisible(true);
 }

}</source>





Focus Traversal: requestFocusInWindow

   <source lang="java">

import java.awt.ruponent; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JFrame; class MouseEnterFocusMover extends MouseAdapter {

 public void mouseEntered(MouseEvent mouseEvent) {
   Component component = mouseEvent.getComponent();
   if (!component.hasFocus()) {
     component.requestFocusInWindow();
   }
 }

} public class FocusSampleMouseEnterFocusMover {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Focus Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   MouseListener mouseListener = new MouseEnterFocusMover();
   frame.setLayout(new GridLayout(3, 3));
   for (int i = 1; i < 10; i++) {
     JButton button = new JButton(Integer.toString(i));
     button.addMouseListener(mouseListener);
     if ((i % 2) != 0) {
       button.setFocusable(false);
     }
     frame.add(button);
   }
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>





JComponent.setFocusTraversalKeys(int arg0, Set<? extends AWTKeyStroke> arg1)

   <source lang="java">

import java.awt.AWTKeyStroke; import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.JButton; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton("a");
   Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(component
       .getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
   set.add(KeyStroke.getKeyStroke("F2"));
   component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
 }

}</source>





JComponent.WHEN_IN_FOCUSED_WINDOW

   <source lang="java">

import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton();
   MyAction action = new MyAction();
   component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
       action.getValue(Action.NAME));
 }

} class MyAction extends AbstractAction {

 public MyAction() {
   super("my action");
 }
 public void actionPerformed(ActionEvent e) {
   System.out.println("hi");
 }

}</source>





KeyboardFocusManager

Tab and Shift-Tab are used for keyboard focus traversal.

To define your own traversal keys: replace or append to a key set via the setFocusTraversalKeys() method of Component.

FORWARD_ TRAVERSAL_KEYS, BACKWARD_TRAVERSAL_KEYS, and UP_CYCLE_TRAVERSAL_KEYS constants of KeyboardFocusManager are for forward, backward, and up-cycle.

To add the "A" key as an up-cycle key for a component



   <source lang="java">

import java.awt.AWTKeyStroke; import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; public class KeyboardFocusManagerDemo {

 public static void main(String[] args) {
   JFrame aWindow = new JFrame("This is a Border Layout");
   aWindow.setBounds(30, 30, 300, 300); // Size
   aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPanel p = new JPanel();
   p.add(new JTextField(10));
   p.add(new JTextField(10));
   p.add(new JTextField(10));
   p.add(new JTextField(10));
   p.add(new JTextField(10));
   p.add(new JTextField(10));
   Set<AWTKeyStroke> set = p.getFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS);
   set = new HashSet(set);
   KeyStroke up = KeyStroke.getKeyStroke("A");
   set.add(up);
   System.out.println(set);
   p.setFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, set);
   aWindow.add(p);
   aWindow.setVisible(true); // Display the window
 }

}</source>





KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS

   <source lang="java">

import java.awt.AWTKeyStroke; import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(KeyboardFocusManager
       .getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(
           KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
   set.add(KeyStroke.getKeyStroke("F3"));
   KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(
       KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set);
 }

}</source>





KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS

   <source lang="java">

import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.JButton; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton("a");
   Set set = new HashSet(component
       .getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
   set.add(KeyStroke.getKeyStroke("F2"));
   component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
 }

}</source>





KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner()

   <source lang="java">

import java.awt.KeyboardFocusManager; public class Main {

 public static void main(String[] argv) throws Exception {
   KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
 }

}</source>





KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)

   <source lang="java">

import java.awt.AWTKeyStroke; import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(KeyboardFocusManager
       .getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(
           KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
   set.add(KeyStroke.getKeyStroke("F3"));
   KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(
       KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set);
 }

}</source>





Listening to All Key Events Before Delivery to Focused Component

   <source lang="java">

import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.event.KeyEvent; public class Main {

 public static void main(String[] argv) throws Exception {
   KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(
       new KeyEventDispatcher() {
         public boolean dispatchKeyEvent(KeyEvent e) {
           if (e.getID() == KeyEvent.KEY_TYPED) {
             e.setKeyChar("a");
           }
           boolean discardEvent = false;
           return discardEvent;
         }
       });
 }

}</source>





Make sure that my Text field has the focus when a JFrame is created

   <source lang="java">

import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JTextField; class MyFrame extends JFrame {

 JTextField field1;
 public MyFrame() {
   field1 = new JTextField(10);
   getContentPane().add("Center", field1);
   addWindowListener(new WindowAdapter() {
     public void windowOpened(WindowEvent e) {
       field1.requestFocus();
     }
   });
   pack();
   setVisible(true);
 }

} public class Main {

 public static void main(String[] argv) {
   MyFrame myFrame = new MyFrame();
 }

}</source>





Moving focus to the next component: focusNextComponent()

   <source lang="java">

import java.awt.GridLayout; import java.awt.KeyboardFocusManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; class ActionFocusMover implements ActionListener {

 public void actionPerformed(ActionEvent actionEvent) {
   KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
   manager.focusNextComponent();
 }

} public class FocusSampleActionFocusMover {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Focus Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   ActionListener actionListener = new ActionFocusMover();
   frame.setLayout(new GridLayout(3, 3));
   for (int i = 1; i < 10; i++) {
     JButton button = new JButton(Integer.toString(i));
     button.addActionListener(actionListener);
     if ((i % 2) != 0) {
       button.setFocusable(false);
     }
     frame.add(button);
   }
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>





No Focus Button

   <source lang="java">

class NoFocusButton extends JButton {

 public NoFocusButton(String s) {
   super(s);
 }
 public boolean isRequestFocusEnabled() {
   return false;
 }
 public boolean isFocusTraversable() {
   return false;
 }

}</source>





Null is returned if none of the components in this application has the focus

   <source lang="java">

import java.awt.ruponent; import java.awt.KeyboardFocusManager; public class Main {

 public static void main() {
   Component compFocusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager()
       .getFocusOwner();
 }

}</source>





Null is returned if none of the windows in this application has the focus

   <source lang="java">

import java.awt.KeyboardFocusManager; import java.awt.Window; public class Main {

 public static void main() {
   Window windowFocusOwner =
   KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
 }

}</source>





Predefined Focus Traversal Policies

PolicyMeaningContainerOrderFocusTraversalPolicyThe components are traversed in the order they are added to their container.DefaultFocusTraversalPolicyThe default policy for AWT programs,InternalFrameFocusTraversalPolicySpecial policy for JInternalFrameSortingFocusTraversalPolicyyour Comparator to the policy constructor to define the focus cycle order.LayoutFocusTraversalPolicyThe default policy for Swing programs, this takes into account geometric settings of components (height, width, position), and then goes top down, left to right to determine navigation order. The top-down, left-right order is determined by the current ComponentOrientation setting for your locale. For instance, Hebrew would be in right-left order instead.


Removing the Focus from the Application

   <source lang="java">

import java.awt.KeyboardFocusManager; public class Main {

 public static void main(String[] argv) throws Exception {
   KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
 }

}</source>





Request Focus inside a window

   <source lang="java">

import java.awt.AWTEventMulticaster; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JTextField; public class KeyTextComponent extends JComponent {

 private ActionListener actionListenerList = null;
 public KeyTextComponent() {
   setBackground(Color.CYAN);
   KeyListener internalKeyListener = new KeyAdapter() {
     public void keyPressed(KeyEvent keyEvent) {
       if (actionListenerList != null) {
         int keyCode = keyEvent.getKeyCode();
         String keyText = KeyEvent.getKeyText(keyCode);
         ActionEvent actionEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, keyText);
         actionListenerList.actionPerformed(actionEvent);
       }
     }
   };
   MouseListener internalMouseListener = new MouseAdapter() {
     public void mousePressed(MouseEvent mouseEvent) {
       requestFocusInWindow();
     }
   };
   addKeyListener(internalKeyListener);
   addMouseListener(internalMouseListener);
 }
 public void addActionListener(ActionListener actionListener) {
   actionListenerList = AWTEventMulticaster.add(actionListenerList, actionListener);
 }
 public void removeActionListener(ActionListener actionListener) {
   actionListenerList = AWTEventMulticaster.remove(actionListenerList, actionListener);
 }
 public boolean isFocusable() {
   return true;
 }
 public static void main(String[] a){
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.add(new KeyTextComponent(), BorderLayout.CENTER);
   JTextField field = new JTextField();
   field.setText("Click above blank area to request focus");
   frame.add(field, BorderLayout.SOUTH);
   frame.setSize(300, 100);
   frame.setVisible(true);
   field.requestFocus();
 }

}</source>





Restricting the Focus Cycle

   <source lang="java">

import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class FocusCycleSample {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Focus Cycle Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setLayout(new GridLayout(3,3));
   for (int i = 0; i < 3; i++) {
     JButton button = new JButton("" + i);
     frame.add(button);
   }
   JPanel panel = new JPanel();
   panel.setFocusCycleRoot(true);
   panel.setFocusTraversalPolicyProvider(true);
   panel.setLayout(new GridLayout(1, 3));
   for (int i = 0; i < 3; i++) {
     JButton button = new JButton("" + (i + 3));
     panel.add(button);
   }
   frame.add(panel);
   for (int i = 0; i < 3; i++) {
     JButton button = new JButton("" + (i + 6));
     frame.add(button);
   }
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>





Reversing Focus Traversal

   <source lang="java">

import java.awt.ruponent; import java.awt.Container; import java.awt.FocusTraversalPolicy; import java.awt.GridLayout; import java.util.Arrays; import java.util.ruparator; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SortingFocusTraversalPolicy; public class NextComponentSample {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Reverse Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setLayout(new GridLayout(3, 3));
   for (int i = 0; i < 9; i++) {
     JButton button = new JButton(Integer.toString(i));
     frame.add(button);
   }
   final Container contentPane = frame.getContentPane();
   Comparator<Component> comp = new Comparator<Component>() {
     public int compare(Component c1, Component c2) {
       Component comps[] = contentPane.getComponents();
       List list = Arrays.asList(comps);
       int first = list.indexOf(c1);
       int second = list.indexOf(c2);
       return second - first;
     }
   };
   FocusTraversalPolicy policy = new SortingFocusTraversalPolicy(comp);
   frame.setFocusTraversalPolicy(policy);
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>





Setting Focus Traversal Keys for the Entire Application

   <source lang="java">

import java.awt.AWTKeyStroke; import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>(KeyboardFocusManager
       .getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(
           KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
   set.add(KeyStroke.getKeyStroke("F2"));
   KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(
       KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
 }

}</source>





Use FocusTraversalPolicy

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.BorderLayout; import java.awt.ruponent; import java.awt.Container; import java.awt.FocusTraversalPolicy; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /*

* FocusTraversalDemo.java requires no other files.
*/

public class FocusTraversalDemo extends JPanel implements ActionListener {

 static JFrame frame;
 JLabel label;
 JCheckBox togglePolicy;
 static MyOwnFocusTraversalPolicy newPolicy;
 public FocusTraversalDemo() {
   super(new BorderLayout());
   JTextField tf1 = new JTextField("Field 1");
   JTextField tf2 = new JTextField("A Bigger Field 2");
   JTextField tf3 = new JTextField("Field 3");
   JTextField tf4 = new JTextField("A Bigger Field 4");
   JTextField tf5 = new JTextField("Field 5");
   JTextField tf6 = new JTextField("A Bigger Field 6");
   JTable table = new JTable(4, 3);
   togglePolicy = new JCheckBox("Custom FocusTraversalPolicy");
   togglePolicy.setActionCommand("toggle");
   togglePolicy.addActionListener(this);
   togglePolicy.setFocusable(false); // Remove it from the focus cycle.
   // Note that HTML is allowed and will break this run of text
   // across two lines.
   label = new JLabel(
       "<html>Use Tab (or Shift-Tab) to navigate from component to component.Control-Tab (or Control-Shift-Tab) allows you to break out of the JTable.</html>");
   JPanel leftTextPanel = new JPanel(new GridLayout(3, 2));
   leftTextPanel.add(tf1, BorderLayout.PAGE_START);
   leftTextPanel.add(tf3, BorderLayout.CENTER);
   leftTextPanel.add(tf5, BorderLayout.PAGE_END);
   leftTextPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));
   JPanel rightTextPanel = new JPanel(new GridLayout(3, 2));
   rightTextPanel.add(tf2, BorderLayout.PAGE_START);
   rightTextPanel.add(tf4, BorderLayout.CENTER);
   rightTextPanel.add(tf6, BorderLayout.PAGE_END);
   rightTextPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 5));
   JPanel tablePanel = new JPanel(new GridLayout(0, 1));
   tablePanel.add(table, BorderLayout.CENTER);
   tablePanel.setBorder(BorderFactory.createEtchedBorder());
   JPanel bottomPanel = new JPanel(new GridLayout(2, 1));
   bottomPanel.add(togglePolicy, BorderLayout.PAGE_START);
   bottomPanel.add(label, BorderLayout.PAGE_END);
   add(leftTextPanel, BorderLayout.LINE_START);
   add(rightTextPanel, BorderLayout.CENTER);
   add(tablePanel, BorderLayout.LINE_END);
   add(bottomPanel, BorderLayout.PAGE_END);
   setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
   Vector<Component> order = new Vector<Component>(7);
   order.add(tf1);
   order.add(tf2);
   order.add(tf3);
   order.add(tf4);
   order.add(tf5);
   order.add(tf6);
   order.add(table);
   newPolicy = new MyOwnFocusTraversalPolicy(order);
 }
 // Turn the custom focus traversal policy on/off,
 // according to the checkbox
 public void actionPerformed(ActionEvent e) {
   if ("toggle".equals(e.getActionCommand())) {
     frame.setFocusTraversalPolicy(togglePolicy.isSelected() ? newPolicy
         : null);
   }
 }
 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   // Create and set up the window.
   frame = new JFrame("FocusTraversalDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   // Create and set up the content pane.
   JComponent newContentPane = new FocusTraversalDemo();
   newContentPane.setOpaque(true); // content panes must be opaque
   frame.setContentPane(newContentPane);
   // Display the window.
   frame.pack();
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   /* Use an appropriate Look and Feel */
   try {
     // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
     // UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
     UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
   } catch (UnsupportedLookAndFeelException ex) {
     ex.printStackTrace();
   } catch (IllegalAccessException ex) {
     ex.printStackTrace();
   } catch (InstantiationException ex) {
     ex.printStackTrace();
   } catch (ClassNotFoundException ex) {
     ex.printStackTrace();
   }
   /* Turn off metal"s use of bold fonts */
   UIManager.put("swing.boldMetal", Boolean.FALSE);
   // Schedule a job for the event-dispatching thread:
   // creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }
 public static class MyOwnFocusTraversalPolicy extends FocusTraversalPolicy {
   Vector<Component> order;
   public MyOwnFocusTraversalPolicy(Vector<Component> order) {
     this.order = new Vector<Component>(order.size());
     this.order.addAll(order);
   }
   public Component getComponentAfter(Container focusCycleRoot,
       Component aComponent) {
     int idx = (order.indexOf(aComponent) + 1) % order.size();
     return order.get(idx);
   }
   public Component getComponentBefore(Container focusCycleRoot,
       Component aComponent) {
     int idx = order.indexOf(aComponent) - 1;
     if (idx < 0) {
       idx = order.size() - 1;
     }
     return order.get(idx);
   }
   public Component getDefaultComponent(Container focusCycleRoot) {
     return order.get(0);
   }
   public Component getLastComponent(Container focusCycleRoot) {
     return order.lastElement();
   }
   public Component getFirstComponent(Container focusCycleRoot) {
     return order.get(0);
   }
 }

}</source>





Use isFocusOwner to determine whether a particular component has the focus

   <source lang="java">

import javax.swing.JFrame; public class Main {

 public static void main() {
   JFrame f = new JFrame();
   boolean b = f.isFocusOwner();
 }

}</source>





Use KeyboardFocusManager

   <source lang="java">

import java.awt.KeyboardFocusManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JFrame; import javax.swing.JTextField; public class UsingFocusListener {

 public static void main(String[] a) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTextField textField = new JTextField("A TextField");
   KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
   focusManager.addPropertyChangeListener(new PropertyChangeListener() {
     public void propertyChange(PropertyChangeEvent e) {
       String prop = e.getPropertyName();
       System.out.println(prop);
     }
   });
   frame.add(textField, "North");
   frame.add(new JTextField(), "South");
   frame.setSize(300, 200);
   frame.setVisible(true);
 }

}</source>