Java/Swing JFC/Focus
Содержание
- 1 Button Focus
- 2 Focus Concepts Demo
- 3 Focus Cycle Sample
- 4 Focus Example
- 5 Focus Traversal Demo
- 6 Focus Traversal Example
- 7 Handling Focus Changes
- 8 Requests focus for a component
- 9 Requests focus unless the component already has focus
- 10 Track Focus Demo
- 11 Use this method to determine whether a particular component has the focus
Button Focus
import java.awt.Container;
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("Action Sample");
JButton focusButton = new JButton("Focused");
JButton notFocusButton = new JButton("Not Focused");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(focusButton);
contentPane.add(notFocusButton);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
Focus Concepts Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 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:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution 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, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/*
* FocusConceptsDemo.java is a 1.4 example that requires no other files.
*/
public class FocusConceptsDemo extends JPanel {
static JFrame frame;
JTextField t1, t2, t3, t4;
JButton b1, b2, b3, b4;
JTextArea text1;
public FocusConceptsDemo() {
super(new BorderLayout());
b1 = new JButton("JButton");
b2 = new JButton("JButton");
b3 = new JButton("JButton");
b4 = new JButton("JButton");
JPanel buttonPanel = new JPanel(new GridLayout(1, 1));
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
buttonPanel.add(b4);
text1 = new JTextArea("JTextArea", 15, 40);
JPanel textAreaPanel = new JPanel(new BorderLayout());
textAreaPanel.add(text1, BorderLayout.CENTER);
t1 = new JTextField("JTextField");
t2 = new JTextField("JTextField");
t3 = new JTextField("JTextField");
t4 = new JTextField("JTextField");
JPanel textFieldPanel = new JPanel(new GridLayout(1, 1));
textFieldPanel.add(t1);
textFieldPanel.add(t2);
textFieldPanel.add(t3);
textFieldPanel.add(t4);
add(buttonPanel, BorderLayout.PAGE_START);
add(textAreaPanel, BorderLayout.CENTER);
add(textFieldPanel, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
frame = new JFrame("FocusConceptsDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new FocusConceptsDemo();
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) {
//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();
}
});
}
}
Focus Cycle Sample
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(3,3));
for (int i = 0; i < 8; i++) {
JButton button = new JButton("" + i);
contentPane.add(button);
}
JPanel panel = new FocusCycleConstrainedJPanel();
panel.setLayout(new GridLayout(1, 3));
for (int i = 0; i < 3; i++) {
JButton button = new JButton("" + (i + 3));
panel.add(button);
}
contentPane.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class FocusCycleConstrainedJPanel extends JPanel {
public boolean isFocusCycleRoot() {
return true;
}
}
Focus Example
import java.awt.AWTKeyStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
public class FocusExample extends JFrame {
public FocusExample() {
super("Focus Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
MyPanel mypanel = new MyPanel();
JButton button1 = new JButton("One");
JButton button2 = new JButton("Two");
JButton button3 = new JButton("Three");
JButton button4 = new JButton("Four");
JButton button5 = new MyButton("Five*");
JButton button6 = new MyButton("Six*");
JButton button7 = new JButton("Seven");
mypanel.add(button2);
mypanel.add(button3);
JInternalFrame frame1 = new JInternalFrame("Internal Frame 1", true,
true, true, true);
frame1.setBackground(Color.lightGray);
frame1.getContentPane().setLayout(new GridLayout(2, 3));
frame1.setSize(300, 200);
frame1.getContentPane().add(button1);
frame1.getContentPane().add(mypanel);
frame1.getContentPane().add(button4);
frame1.getContentPane().add(button5);
frame1.getContentPane().add(button6);
frame1.getContentPane().add(button7);
JDesktopPane desktop = new JDesktopPane();
desktop.add(frame1, new Integer(1));
desktop.setOpaque(true);
// Now set up the user interface window.
Container contentPane = getContentPane();
contentPane.add(desktop, BorderLayout.CENTER);
setSize(new Dimension(400, 300));
frame1.setVisible(true);
setVisible(true);
}
public static void main(String[] args) {
new FocusExample();
}
class MyButton extends JButton {
public MyButton(String s) {
super(s);
}
public boolean isFocusable() {
return false;
}
}
class MyPanel extends JPanel {
public MyPanel() {
super(true);
java.util.Set upKeys = new java.util.HashSet(1);
upKeys.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_UP, 0));
setFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS,
upKeys);
}
public boolean isFocusCycleRoot() {
return true;
}
}
}
Focus Traversal Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 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:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution 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, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
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 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;
/*
* FocusTraversalDemo.java is a 1.4 example that requires no other files.
*/
public class FocusTraversalDemo extends JPanel implements ActionListener {
static JFrame frame;
JTextField tf1, tf2, tf3, tf4, tf5, tf6;
JTable table;
JLabel label;
JCheckBox togglePolicy;
static MyOwnFocusTraversalPolicy newPolicy;
public FocusTraversalDemo() {
super(new BorderLayout());
newPolicy = new MyOwnFocusTraversalPolicy();
tf1 = new JTextField("Field 1");
tf2 = new JTextField("A Bigger Field 2");
tf3 = new JTextField("Field 3");
tf4 = new JTextField("A Bigger Field 4");
tf5 = new JTextField("Field 5");
tf6 = new JTextField("A Bigger Field 6");
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.<p>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));
}
//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() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//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) {
//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 class MyOwnFocusTraversalPolicy extends FocusTraversalPolicy {
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
if (aComponent.equals(tf1)) {
return tf2;
} else if (aComponent.equals(tf2)) {
return tf3;
} else if (aComponent.equals(tf3)) {
return tf4;
} else if (aComponent.equals(tf4)) {
return tf5;
} else if (aComponent.equals(tf5)) {
return tf6;
} else if (aComponent.equals(tf6)) {
return table;
} else if (aComponent.equals(table)) {
return tf1;
}
return tf1;
}
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
if (aComponent.equals(tf1)) {
return table;
} else if (aComponent.equals(tf2)) {
return tf1;
} else if (aComponent.equals(tf3)) {
return tf2;
} else if (aComponent.equals(tf4)) {
return tf3;
} else if (aComponent.equals(tf5)) {
return tf4;
} else if (aComponent.equals(tf6)) {
return tf5;
} else if (aComponent.equals(table)) {
return tf6;
}
return tf1;
}
public Component getDefaultComponent(Container focusCycleRoot) {
return tf1;
}
public Component getLastComponent(Container focusCycleRoot) {
return table;
}
public Component getFirstComponent(Container focusCycleRoot) {
return tf1;
}
}
}
Focus Traversal Example
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// FocusTraversalExample.java
//Similar to the FocusExample, this class uses the custom AlphaButtonPolicy
//focus traversal policy to navigate another small set of buttons.
//
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import java.awt.GridLayout;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FocusTraversalExample extends JPanel {
public FocusTraversalExample() {
setLayout(new GridLayout(6, 1));
JButton button1 = new JButton("Texas");
JButton button2 = new JButton("Vermont");
JButton button3 = new JButton("Florida");
JButton button4 = new JButton("Alabama");
JButton button5 = new JButton("Minnesota");
JButton button6 = new JButton("California");
setBackground(Color.lightGray);
add(button1);
add(button2);
add(button3);
add(button4);
add(button5);
add(button6);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Alphabetized Button Focus Traversal");
frame.setFocusTraversalPolicy(new AlphaButtonPolicy());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new FocusTraversalExample());
frame.setSize(400, 300);
frame.setVisible(true);
}
}
//AlphaButtonPolicy.java
//A custom focus traversal policy that uses alphabetical ordering of button
//labels to determine "next" and "previous" buttons for keyboard traversal.
//
class AlphaButtonPolicy extends FocusTraversalPolicy {
private SortedMap getSortedButtons(Container focusCycleRoot) {
if (focusCycleRoot == null) {
throw new IllegalArgumentException("focusCycleRoot can"t be null");
}
SortedMap result = new TreeMap(); // Will sort all buttons by text.
sortRecursive(result, focusCycleRoot);
return result;
}
private void sortRecursive(Map buttons, Container container) {
for (int i = 0; i < container.getComponentCount(); i++) {
Component c = container.getComponent(i);
if (c instanceof JButton) { // Found another button to sort.
buttons.put(((JButton) c).getText(), c);
}
if (c instanceof Container) { // Found a container to search.
sortRecursive(buttons, (Container) c);
}
}
}
// The rest of the code implements the FocusTraversalPolicy interface.
public Component getFirstComponent(Container focusCycleRoot) {
SortedMap buttons = getSortedButtons(focusCycleRoot);
if (buttons.isEmpty()) {
return null;
}
return (Component) buttons.get(buttons.firstKey());
}
public Component getLastComponent(Container focusCycleRoot) {
SortedMap buttons = getSortedButtons(focusCycleRoot);
if (buttons.isEmpty()) {
return null;
}
return (Component) buttons.get(buttons.lastKey());
}
public Component getDefaultComponent(Container focusCycleRoot) {
return getFirstComponent(focusCycleRoot);
}
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
if (!(aComponent instanceof JButton)) {
return null;
}
SortedMap buttons = getSortedButtons(focusCycleRoot);
// Find all buttons after the current one.
String nextName = ((JButton) aComponent).getText() + "\0";
SortedMap nextButtons = buttons.tailMap(nextName);
if (nextButtons.isEmpty()) { // Wrapped back to beginning
if (!buttons.isEmpty()) {
return (Component) buttons.get(buttons.firstKey());
}
return null; // Degenerate case of no buttons.
}
return (Component) nextButtons.get(nextButtons.firstKey());
}
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
if (!(aComponent instanceof JButton)) {
return null;
}
SortedMap buttons = getSortedButtons(focusCycleRoot);
SortedMap prevButtons = // Find all buttons before this one.
buttons.headMap(((JButton) aComponent).getText());
if (prevButtons.isEmpty()) { // Wrapped back to end.
if (!buttons.isEmpty()) {
return (Component) buttons.get(buttons.lastKey());
}
return null; // Degenerate case of no buttons.
}
return (Component) prevButtons.get(prevButtons.lastKey());
}
}
Handling Focus Changes
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main {
public static void main(String[] argv) throws Exception {
JTextField component = new JTextField();
component.addFocusListener(new MyFocusListener());
JFrame f = new JFrame();
f.add(component);
f.setSize(300, 300);
f.setVisible(true);
}
}
class MyFocusListener extends FocusAdapter {
public void focusGained(FocusEvent evt) {
System.out.println("component gained the focus");
}
public void focusLost(FocusEvent evt) {
System.out.println("component lost the focus");
}
}
Requests focus for a component
import java.awt.ruponent;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import java.awt.KeyboardFocusManager;
import javax.swing.JComponent;
/**
* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R)
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $
public class Util {
/**
* Requests focus for a component. If that"s not possible it"s
* {@link FocusTraversalPolicy}is checked. If that doesn"t work all it"s
* children is recursively checked with this method.
*
* @param component the component to request focus for
* @return the component which has focus or probably will obtain focus, null
* if no component will receive focus
*/
public static Component smartRequestFocus(Component component) {
if (requestFocus(component))
return component;
if (component instanceof JComponent) {
FocusTraversalPolicy policy = ((JComponent) component).getFocusTraversalPolicy();
if (policy != null) {
Component focusComponent = policy.getDefaultComponent((Container) component);
if (focusComponent != null && requestFocus(focusComponent)) {
return focusComponent;
}
}
}
if (component instanceof Container) {
Component[] children = ((Container) component).getComponents();
for (int i = 0; i < children.length; i++) {
component = smartRequestFocus(children[i]);
if (component != null)
return component;
}
}
return null;
}
/**
* Requests focus unless the component already has focus. For some weird
* reason calling {@link Component#requestFocusInWindow()}when the
* component is focus owner changes focus owner to another component!
*
* @param component the component to request focus for
* @return true if the component has focus or probably will get focus,
* otherwise false
*/
public static boolean requestFocus(Component component) {
/*
* System.out.println("Owner: " +
* System.identityHashCode(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) + ", " +
* System.identityHashCode(component) + ", " +
* (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() ==
* component));
*/
return KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == component ||
component.requestFocusInWindow();
}
}
Requests focus unless the component already has focus
import java.awt.ruponent;
import java.awt.KeyboardFocusManager;
/**
* Copyright (C) 2004 NNL Technology AB
* Visit www.infonode.net for information about InfoNode(R)
* products and how to contact NNL Technology AB.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
// $Id: ComponentUtil.java,v 1.25 2005/12/04 13:46:04 jesper Exp $
public class Util {
/**
* Requests focus unless the component already has focus. For some weird
* reason calling {@link Component#requestFocusInWindow()}when the
* component is focus owner changes focus owner to another component!
*
* @param component the component to request focus for
* @return true if the component has focus or probably will get focus,
* otherwise false
*/
public static boolean requestFocus(Component component) {
/*
* System.out.println("Owner: " +
* System.identityHashCode(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) + ", " +
* System.identityHashCode(component) + ", " +
* (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() ==
* component));
*/
return KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == component ||
component.requestFocusInWindow();
}
}
Track Focus Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 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:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution 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, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
/*
* TrackFocusDemo.java is a 1.4 example that requires the following files:
* Picture.java images/Maya.jpg images/Anya.jpg images/Laine.jpg
* images/Cosmo.jpg images/Adele.jpg images/Alexi.jpg
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.KeyboardFocusManager;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.accessibility.Accessible;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TrackFocusDemo extends JPanel {
Picture pic1, pic2, pic3, pic4, pic5, pic6;
JLabel info;
static String mayaString = "Maya";
static String anyaString = "Anya";
static String laineString = "Laine";
static String cosmoString = "Cosmo";
static String adeleString = "Adele";
static String alexiString = "Alexi";
String[] comments = { "Oops. What is this?", "This is Maya",
"This is Anya", "This is Laine", "This is Cosmo", "This is Adele",
"This is Alexi" };
public TrackFocusDemo() {
super(new BorderLayout());
JPanel mugshots = new JPanel(new GridLayout(2, 3));
pic1 = new Picture(createImageIcon("images/" + mayaString + ".jpg",
mayaString).getImage());
pic1.setName("1");
mugshots.add(pic1);
pic2 = new Picture(createImageIcon("images/" + anyaString + ".jpg",
anyaString).getImage());
pic2.setName("2");
mugshots.add(pic2);
pic3 = new Picture(createImageIcon("images/" + laineString + ".jpg",
laineString).getImage());
pic3.setName("3");
mugshots.add(pic3);
pic4 = new Picture(createImageIcon("images/" + cosmoString + ".jpg",
cosmoString).getImage());
pic4.setName("4");
mugshots.add(pic4);
pic5 = new Picture(createImageIcon("images/" + adeleString + ".jpg",
adeleString).getImage());
pic5.setName("5");
mugshots.add(pic5);
pic6 = new Picture(createImageIcon("images/" + alexiString + ".jpg",
alexiString).getImage());
pic6.setName("6");
mugshots.add(pic6);
info = new JLabel("Nothing selected");
setPreferredSize(new Dimension(450, 350));
add(mugshots, BorderLayout.CENTER);
add(info, BorderLayout.PAGE_END);
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() != null)
&& ((e.getNewValue()) instanceof Picture)) {
Component comp = (Component) e.getNewValue();
String name = comp.getName();
Integer num = new Integer(name);
int index = num.intValue();
if (index < 0 || index > comments.length) {
index = 0;
}
info.setText(comments[index]);
}
}
});
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path, String description) {
java.net.URL imageURL = TrackFocusDemo.class.getResource(path);
if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return new ImageIcon(imageURL, description);
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("TrackFocusDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new TrackFocusDemo();
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) {
//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();
}
});
}
}
/*
* Picture.java is used by the 1.4 TrackFocusDemo.java and DragPictureDemo.java
* examples.
*/
class Picture extends JComponent implements MouseListener, FocusListener,
Accessible {
Image image;
public Picture(Image image) {
this.image = image;
setFocusable(true);
addMouseListener(this);
addFocusListener(this);
}
public void mouseClicked(MouseEvent e) {
//Since the user clicked on us, let"s get focus!
requestFocusInWindow();
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void focusGained(FocusEvent e) {
//Draw the component with a red border
//indicating that it has focus.
this.repaint();
}
public void focusLost(FocusEvent e) {
//Draw the component with a black border
//indicating that it doesn"t have focus.
this.repaint();
}
protected void paintComponent(Graphics graphics) {
Graphics g = graphics.create();
//Draw in our entire space, even if isOpaque is false.
g.setColor(Color.WHITE);
g.fillRect(0, 0, image == null ? 125 : image.getWidth(this),
image == null ? 125 : image.getHeight(this));
if (image != null) {
//Draw image at its natural size of 125x125.
g.drawImage(image, 0, 0, this);
}
//Add a border, red if picture currently has focus
if (isFocusOwner()) {
g.setColor(Color.RED);
} else {
g.setColor(Color.BLACK);
}
g.drawRect(0, 0, image == null ? 125 : image.getWidth(this),
image == null ? 125 : image.getHeight(this));
g.dispose();
}
}
Use this method 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();
}
}