Java/Event/Focus Event — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 05:58, 1 июня 2010
Содержание
- 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 JComponent.setFocusTraversalKeys(int arg0, Set<? extends AWTKeyStroke> arg1)
- 9 KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS
- 10 KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS
- 11 KeyboardFocusManager.getCurrentKeyboardFocusManager().getDefaultFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)
- 12 Listening to All Focus Changes Between Components and windows
- 13 Modify a component: press space bar or F2 to move focus to next focusable component.
- 14 Null is returned if none of the components in this application has the focus
- 15 Null is returned if none of the windows in this application has the focus
- 16 Press shift space or shift F2 to move the focus to the previous focusable component.
- 17 Preventing a Component from Gaining the Focus
- 18 Remove all backward focus traversal keys for the application
- 19 Remove all forward focus traversal keys for the application
- 20 Removing the Focus from the Application
- 21 Setting Focus Traversal Keys for the Entire Application
- 22 Setting Focus Traversal Keys in a Component
- 23 Setting the Initial Focused Component in a Window
- 24 Use Focus Events in Swing
- 25 Validating a JTextField When Permanently Losing the Focus
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;
}
}
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);
}
}
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().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 Focus Changes Between Components and windows
import java.awt.ruponent;
import java.awt.KeyboardFocusManager;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class Main {
public static void main(String[] argv) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(
new FocusChangeListener());
}
}
class FocusChangeListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent evt) {
Component oldComp = (Component) evt.getOldValue();
Component newComp = (Component) evt.getNewValue();
if ("focusOwner".equals(evt.getPropertyName())) {
if (oldComp == null) {
System.out.println(newComp.getName());
} else {
System.out.println(oldComp.getName());
}
} else if ("focusedWindow".equals(evt.getPropertyName())) {
if (oldComp == null) {
System.out.println(newComp.getName());
} else {
System.out.println(oldComp.getName());
}
}
}
}
Modify a component: press space bar or F2 to move focus to next focusable component.
import java.awt.ruponent;
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) {
JButton component = new JButton();
NextFocusAction nextFocusAction = new NextFocusAction();
component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("SPACE"),
nextFocusAction.getValue(Action.NAME));
component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("F2"),
nextFocusAction.getValue(Action.NAME));
component.getActionMap().put(nextFocusAction.getValue(Action.NAME), nextFocusAction);
}
}
class NextFocusAction extends AbstractAction {
public NextFocusAction() {
super("Move Focus Forwards");
}
public void actionPerformed(ActionEvent evt) {
((Component) evt.getSource()).transferFocus();
}
}
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();
}
}
Press shift space or shift F2 to move the focus to the previous focusable component.
import java.awt.ruponent;
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) {
JButton component = new JButton();
PrevFocusAction prevFocusAction = new PrevFocusAction();
component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("shift F2"),
prevFocusAction.getValue(Action.NAME));
component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("shift SPACE"),
prevFocusAction.getValue(Action.NAME));
component.getActionMap().put(prevFocusAction.getValue(Action.NAME), prevFocusAction);
}
}
class PrevFocusAction extends AbstractAction {
PrevFocusAction() {
super("Move Focus Backwards");
}
public void actionPerformed(ActionEvent evt) {
((Component) evt.getSource()).transferFocusBackward();
}
}
Preventing a Component from Gaining the Focus
import javax.swing.JFrame;
public class Main {
public static void main(String[] argv) throws Exception {
JFrame frame = new JFrame();
frame.setFocusable(false);
}
}
Remove all backward focus traversal keys for the application
import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] argv) throws Exception {
Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>();
KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, set);
}
}
Remove all forward focus traversal keys for the application
import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] argv) throws Exception {
Set<AWTKeyStroke> set = new HashSet<AWTKeyStroke>();
KeyboardFocusManager.getCurrentKeyboardFocusManager().setDefaultFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, set);
}
}
Removing the Focus from the Application
import java.awt.KeyboardFocusManager;
public class Main {
public static void main(String[] argv) throws Exception {
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
}
}
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);
}
}
Setting Focus Traversal Keys in 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);
}
}
Setting the Initial Focused Component in a Window
import java.awt.ruponent;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main {
public static void main(String[] argv) throws Exception {
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);
InitialFocusSetter.setInitialFocus(frame, component2);
frame.pack();
frame.setVisible(true);
}
}
class InitialFocusSetter {
public static void setInitialFocus(Window w, Component c) {
w.addWindowListener(new FocusSetter(c));
}
}
class FocusSetter extends WindowAdapter {
Component initComp;
FocusSetter(Component c) {
initComp = c;
}
public void windowOpened(WindowEvent e) {
initComp.requestFocus();
e.getWindow().removeWindowListener(this);
}
}
Use Focus Events in Swing
import java.awt.Dimension;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class Main extends JPanel implements FocusListener {
public Main() {
JTextField textField = new JTextField("A TextField");
textField.addFocusListener(this);
JLabel label = new JLabel("A Label");
label.addFocusListener(this);
add(label);
String comboPrefix = "ComboBox Item #";
final int numItems = 15;
Vector vector = new Vector(numItems);
for (int i = 0; i < numItems; i++) {
vector.addElement(comboPrefix + i);
}
JComboBox comboBox = new JComboBox(vector);
comboBox.addFocusListener(this);
add(comboBox);
JButton button = new JButton("A Button");
button.addFocusListener(this);
add(button);
String listPrefix = "List Item #";
Vector listVector = new Vector(numItems);
for (int i = 0; i < numItems; i++) {
listVector.addElement(listPrefix + i);
}
JList list = new JList(listVector);
list.setSelectedIndex(1);
list.addFocusListener(this);
JScrollPane listScrollPane = new JScrollPane(list);
listScrollPane.getVerticalScrollBar().setFocusable(false);
listScrollPane.getHorizontalScrollBar().setFocusable(false);
add(listScrollPane);
setPreferredSize(new Dimension(450, 450));
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
void displayMessage(String prefix, FocusEvent e) {
System.out.println(prefix
+ (e.isTemporary() ? " (temporary):" : ":")
+ e.getComponent().getClass().getName()
+ "; Opposite component: "
+ (e.getOppositeComponent() != null ? e.getOppositeComponent().getClass().getName()
: "null") );
}
public static void main(String[] args) {
JFrame frame = new JFrame("FocusEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Main();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public void focusGained(FocusEvent e) {
displayMessage("Focus gained", e);
}
public void focusLost(FocusEvent e) {
displayMessage("Focus lost", e);
}
}
Validating a JTextField When Permanently Losing the Focus
import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
public class Main {
public static void main(String[] argv) throws Exception {
JTextField component = new JTextField(10);
JTextField component1 = new JTextField(10);
component.addFocusListener(new MyFocusListener());
component1.addFocusListener(new MyFocusListener());
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
f.add(component1);
f.add(component);
f.pack();
f.setVisible(true);
}
}
class MyFocusListener extends FocusAdapter {
boolean showingDialog = false;
public void focusGained(FocusEvent evt) {
final JTextComponent c = (JTextComponent) evt.getSource();
String s = c.getText();
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
c.setSelectionStart(i);
c.setSelectionEnd(i);
break;
}
}
}
public void focusLost(FocusEvent evt) {
final JTextComponent c = (JTextComponent) evt.getSource();
String s = c.getText();
if (evt.isTemporary()) {
return;
}
for (int i = 0; i < s.length(); i++) {
if (!Character.isDigit(s.charAt(i))) {
System.out.println("must only contain digits");
c.requestFocus();
break;
}
}
}
}