Java KeyboardFocusManager .getFocusOwner ()
Syntax
KeyboardFocusManager.getFocusOwner() has the following syntax.
public Component getFocusOwner()
Example
In the following code shows how to use KeyboardFocusManager.getFocusOwner() method.
// w ww . ja v a 2 s.co m
import java.awt.Component;
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;
}
}
Home »
Java Tutorial »
java.awt »
Java Tutorial »
java.awt »