Java/Event/Focus Event
Содержание
- 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.
<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>
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>
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().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 Focus Changes Between Components and windows
<source lang="java">
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()); } } }
}
</source>
Modify a component: press space bar or F2 to move focus to next focusable component.
<source lang="java">
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(); }
}
</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>
Press shift space or shift F2 to move the focus to the previous focusable component.
<source lang="java">
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(); }
}
</source>
Preventing a Component from Gaining the Focus
<source lang="java">
import javax.swing.JFrame; public class Main {
public static void main(String[] argv) throws Exception { JFrame frame = new JFrame(); frame.setFocusable(false); }
}
</source>
Remove all 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; 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); }
}
</source>
Remove all forward 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; 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); }
}
</source>
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>
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>
Setting Focus Traversal Keys in 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>
Setting the Initial Focused Component in a Window
<source lang="java">
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); }
}
</source>
Use Focus Events in Swing
<source lang="java">
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);
} }
</source>
Validating a JTextField When Permanently Losing the Focus
<source lang="java">
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; } } }
}
</source>