Java Tutorial/Swing Event/Focus
Содержание
- 1 Changes the focus traversal keys for the entire application.
- 2 Change the backward focus traversal keys for the application
- 3 Change the forward focus traversal keys for a component
- 4 Determining If a Focus Lost Is Temporary or Permanent
- 5 Determining the Opposite Component of a Focus Event
- 6 Finding the Next Focusable Component
- 7 Find the previous focusable component
- 8 Focus auto-setting
- 9 Focus Traversal: requestFocusInWindow
- 10 JComponent.setFocusTraversalKeys(int arg0, Set<? extends AWTKeyStroke> arg1)
- 11 JComponent.WHEN_IN_FOCUSED_WINDOW
- 12 KeyboardFocusManager
- 13 KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS
- 14 KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS
- 15 KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner()
- 16 KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)
- 17 Listening to All Key Events Before Delivery to Focused Component
- 18 Make sure that my Text field has the focus when a JFrame is created
- 19 Moving focus to the next component: focusNextComponent()
- 20 No Focus Button
- 21 Null is returned if none of the components in this application has the focus
- 22 Null is returned if none of the windows in this application has the focus
- 23 Predefined Focus Traversal Policies
- 24 Removing the Focus from the Application
- 25 Request Focus inside a window
- 26 Restricting the Focus Cycle
- 27 Reversing Focus Traversal
- 28 Setting Focus Traversal Keys for the Entire Application
- 29 Use FocusTraversalPolicy
- 30 Use isFocusOwner to determine whether a particular component has the focus
- 31 Use KeyboardFocusManager
Changes the focus traversal keys for the entire application.
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);
}
}
Change the backward focus traversal keys for the application
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);
}
}
Change the forward focus traversal keys for a component
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);
}
}
Determining If a Focus Lost Is Temporary or Permanent
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();
}
}
Determining the Opposite Component of a Focus Event
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");
}
}
Finding the Next Focusable Component
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;
}
}
Find the previous focusable component
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;
}
}
Focus auto-setting
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);
}
}
Focus Traversal: requestFocusInWindow
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);
}
}
JComponent.setFocusTraversalKeys(int arg0, Set<? extends AWTKeyStroke> arg1)
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);
}
}
JComponent.WHEN_IN_FOCUSED_WINDOW
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");
}
}
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
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
}
}
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS
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);
}
}
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS
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);
}
}
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner()
import java.awt.KeyboardFocusManager;
public class Main {
public static void main(String[] argv) throws Exception {
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
}
}
KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)
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);
}
}
Listening to All Key Events Before Delivery to Focused Component
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;
}
});
}
}
Make sure that my Text field has the focus when a JFrame is created
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();
}
}
Moving focus to the next component: focusNextComponent()
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);
}
}
No Focus Button
class NoFocusButton extends JButton {
public NoFocusButton(String s) {
super(s);
}
public boolean isRequestFocusEnabled() {
return false;
}
public boolean isFocusTraversable() {
return false;
}
}
Null is returned if none of the components in this application has the focus
import java.awt.ruponent;
import java.awt.KeyboardFocusManager;
public class Main {
public static void main() {
Component compFocusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager()
.getFocusOwner();
}
}
Null is returned if none of the windows in this application has the focus
import java.awt.KeyboardFocusManager;
import java.awt.Window;
public class Main {
public static void main() {
Window windowFocusOwner =
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
}
}
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
import java.awt.KeyboardFocusManager;
public class Main {
public static void main(String[] argv) throws Exception {
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
}
}
Request Focus inside a window
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();
}
}
Restricting the Focus Cycle
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);
}
}
Reversing Focus Traversal
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);
}
}
Setting Focus Traversal Keys for the Entire Application
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);
}
}
Use FocusTraversalPolicy
/*
* 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);
}
}
}
Use isFocusOwner to determine whether a particular component has the focus
import javax.swing.JFrame;
public class Main {
public static void main() {
JFrame f = new JFrame();
boolean b = f.isFocusOwner();
}
}
Use KeyboardFocusManager
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);
}
}