下面列出了怎么用java.awt.KeyboardFocusManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void actionPerformed(ActionEvent evt) {
Component cFocusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
if (cFocusOwner instanceof JComponent) {
if (cFocusOwner.isEnabled()) {
// Cut all selected UserObjects from the tree
if (cFocusOwner instanceof EditableComponent) {
((EditableComponent) cFocusOwner).cutSelectedItems();
}
}
}
// "Old" version with JHotDraw clipboard
// JComponent cTarget = target;
//
// if (cTarget == null && (cFocusOwner instanceof JComponent)) {
// cTarget = (JComponent) cFocusOwner;
// }
//
// if (cTarget != null && cTarget.isEnabled() && cTarget.getTransferHandler() != null) {
// cTarget.getTransferHandler().exportToClipboard(cTarget, ClipboardUtil.getClipboard(), TransferHandler.MOVE);
// }
}
@Override
public void actionPerformed(ActionEvent evt) {
Component cFocusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
if (cFocusOwner instanceof JComponent) {
if (cFocusOwner.isEnabled()) {
// Cut all selected UserObjects from the tree
if (cFocusOwner instanceof EditableComponent) {
((EditableComponent) cFocusOwner).copySelectedItems();
}
}
}
// "Old" version with JHotDraw clipboard
// JComponent cTarget = target;
//
// if (cTarget == null && (cFocusOwner instanceof JComponent)) {
// cTarget = (JComponent) cFocusOwner;
// }
// // Note: copying is allowed for disabled components
// if (cTarget != null && cTarget.getTransferHandler() != null) {
// cTarget.getTransferHandler().exportToClipboard(cTarget, ClipboardUtil.getClipboard(), TransferHandler.COPY);
// }
}
@SuppressWarnings("deprecation")
private static void maybeInitializeFocusPolicy(JComponent comp) {
// Check for JRootPane which indicates that a swing toplevel
// is coming, in which case a swing default focus policy
// should be instatiated. See 7125044.
if (comp instanceof JRootPane) {
synchronized (classLock) {
if (!getLAFState().focusPolicyInitialized) {
getLAFState().focusPolicyInitialized = true;
if (FocusManager.isFocusManagerEnabled()) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
setDefaultFocusTraversalPolicy(
new LayoutFocusTraversalPolicy());
}
}
}
}
}
void test1(final TestCase t) {
Runnable action = new Runnable() {
public void run() {
KeyboardFocusManager.setCurrentKeyboardFocusManager(new TestKFM());
if (t == TestCase.REMOVAL) {
frame.remove(frame.panel0);
} else if (t == TestCase.HIDING) {
frame.panel0.setVisible(false);
}
frame.repaint();
}
};
if (!Util.trackFocusGained(frame.b3, action, 2000, false)) {
throw new TestFailedException(t + ": focus wasn't transfered as expected!");
}
KeyboardFocusManager.setCurrentKeyboardFocusManager(kfm);
}
public static void main(String[] args) {
boolean all_passed = true;
KeyboardFocusManager testKFM = new TestKFM(robot);
KeyboardFocusManager defKFM = KeyboardFocusManager.getCurrentKeyboardFocusManager();
for (int i = 0; i < 10; i++) {
test(testKFM, defKFM);
Util.waitForIdle(robot);
System.out.println("Iter " + i + ": " + (lock.get() ? "passed." : "failed!"));
if (!lock.get()) {
all_passed = false;
}
}
if (!all_passed) {
throw new RuntimeException("Test failed: not all iterations passed!");
}
System.out.println("Test passed.");
}
/** Overridden to hide the selection when not focused, and paint across the
* selected row if focused. */
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Object value = getValueAt(row, col);
Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
boolean isSelected = isSelected(row, focusOwner);
Component result = renderer.getTableCellRendererComponent(this, value, isSelected, false, row, col);
if( PropUtils.isNimbus ) {
//HACK to get rid of alternate row background colors
if( !isSelected ) {
Color bkColor = getBackground();
if( null != bkColor )
result.setBackground( new Color( bkColor.getRGB() ) );
}
}
return result;
}
public static void main(String[] args) {
boolean all_passed = true;
KeyboardFocusManager testKFM = new TestKFM(robot);
KeyboardFocusManager defKFM = KeyboardFocusManager.getCurrentKeyboardFocusManager();
for (int i = 0; i < 10; i++) {
test(testKFM, defKFM);
Util.waitForIdle(robot);
System.out.println("Iter " + i + ": " + (lock.get() ? "passed." : "failed!"));
if (!lock.get()) {
all_passed = false;
}
}
if (!all_passed) {
throw new RuntimeException("Test failed: not all iterations passed!");
}
System.out.println("Test passed.");
}
@Override
public void setVisible(boolean visible) {
boolean oldVisible = isVisible();
super.setVisible(visible);
JRootPane rootPane = SwingUtilities.getRootPane(this);
if ((rootPane != null) && (isVisible() != oldVisible)) {
if (isVisible()) {
Component focusOwner = KeyboardFocusManager.
getCurrentKeyboardFocusManager().getPermanentFocusOwner();
if ((focusOwner != null) &&
SwingUtilities.isDescendingFrom(focusOwner, rootPane)) {
recentFocusOwner = focusOwner;
}
rootPane.getLayeredPane().setVisible(false);
requestFocusInWindow();
} else {
rootPane.getLayeredPane().setVisible(true);
if (recentFocusOwner != null) {
recentFocusOwner.requestFocusInWindow();
}
recentFocusOwner = null;
}
}
}
private void initOtherVariables() {
// add keyboard listener to be able to set events on the wanted keys
boxKeyEventDispatch = new BBoxWinKeyEventDispatcher();
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(boxKeyEventDispatch);
// display a label with the object id
displayObjId();
// add the size of the object
setFrameTitle();
enableScribbleObjOpt(currentObject instanceof ObjectScribble);
// compute the preffered width of the combo boxes based on the specified text
jCBObjType.setPrototypeDisplayValue(Constants.OBJECT_ATTRIBUTES_TEXT);
jCBObjClass.setPrototypeDisplayValue(Constants.OBJECT_ATTRIBUTES_TEXT);
jCBObjValue.setPrototypeDisplayValue(Constants.OBJECT_ATTRIBUTES_TEXT);
}
public static void main(String[] args) {
boolean all_passed = true;
KeyboardFocusManager testKFM = new TestKFM(robot);
KeyboardFocusManager defKFM = KeyboardFocusManager.getCurrentKeyboardFocusManager();
for (int i = 0; i < 10; i++) {
test(testKFM, defKFM);
Util.waitForIdle(robot);
System.out.println("Iter " + i + ": " + (lock.get() ? "passed." : "failed!"));
if (!lock.get()) {
all_passed = false;
}
}
if (!all_passed) {
throw new RuntimeException("Test failed: not all iterations passed!");
}
System.out.println("Test passed.");
}
public void dispose() {
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.removeKeyEventDispatcher(keyEventDispatcher);
Configuration.autoDeobfuscate.removeListener(configListenerAutoDeobfuscate);
Configuration.simplifyExpressions.removeListener(configListenerSimplifyExpressions);
Configuration.internalFlashViewer.removeListener(configListenerInternalFlashViewer);
Configuration.parallelSpeedUp.removeListener(configListenerParallelSpeedUp);
Configuration.decompile.removeListener(configListenerDecompile);
//Configuration.cacheOnDisk.removeListener(configListenerCacheOnDisk);
Configuration.gotoMainClassOnStartup.removeListener(configListenerGotoMainClassOnStartup);
Configuration.autoRenameIdentifiers.removeListener(configListenerAutoRenameIdentifiers);
Configuration.autoOpenLoadedSWFs.removeListener(configListenerAutoOpenLoadedSWFs);
Main.stopRun();
}
private static void maybeInitializeFocusPolicy(JComponent comp) {
// Check for JRootPane which indicates that a swing toplevel
// is coming, in which case a swing default focus policy
// should be instatiated. See 7125044.
if (comp instanceof JRootPane) {
synchronized (classLock) {
if (!getLAFState().focusPolicyInitialized) {
getLAFState().focusPolicyInitialized = true;
if (FocusManager.isFocusManagerEnabled()) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
setDefaultFocusTraversalPolicy(
new LayoutFocusTraversalPolicy());
}
}
}
}
}
void test1(final TestCase t) {
Runnable action = new Runnable() {
public void run() {
KeyboardFocusManager.setCurrentKeyboardFocusManager(new TestKFM());
if (t == TestCase.REMOVAL) {
frame.remove(frame.panel0);
} else if (t == TestCase.HIDING) {
frame.panel0.setVisible(false);
}
frame.repaint();
}
};
if (!Util.trackFocusGained(frame.b3, action, 2000, false)) {
throw new TestFailedException(t + ": focus wasn't transfered as expected!");
}
KeyboardFocusManager.setCurrentKeyboardFocusManager(kfm);
}
private static boolean isWaitCursor() {
Component focus = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (focus != null) {
if (focus.getCursor().getType() == Cursor.WAIT_CURSOR) {
LOG.finer("wait cursor on focus owner"); // NOI18N
return true;
}
Window w = SwingUtilities.windowForComponent(focus);
if (w != null && isWaitCursorOnWindow(w)) {
LOG.finer("wait cursor on window"); // NOI18N
return true;
}
}
for (Frame f : Frame.getFrames()) {
if (isWaitCursorOnWindow(f)) {
LOG.finer("wait cursor on frame"); // NOI18N
return true;
}
}
LOG.finest("no wait cursor"); // NOI18N
return false;
}
private Window findFocusWindow() {
Window w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
if (w != null)
return w;
w = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
if (w != null)
return w;
Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if (focusOwner != null)
w = SwingUtilities.getWindowAncestor(focusOwner);
if (w != null)
return w;
Window[] validWindows = getValidWindows();
if (validWindows.length > 0)
return validWindows[validWindows.length - 1];
return null;
}
private static void maybeInitializeFocusPolicy(JComponent comp) {
// Check for JRootPane which indicates that a swing toplevel
// is coming, in which case a swing default focus policy
// should be instatiated. See 7125044.
if (comp instanceof JRootPane) {
synchronized (classLock) {
if (!getLAFState().focusPolicyInitialized) {
getLAFState().focusPolicyInitialized = true;
if (FocusManager.isFocusManagerEnabled()) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
setDefaultFocusTraversalPolicy(
new LayoutFocusTraversalPolicy());
}
}
}
}
}
protected void componentActivated() {
super.componentActivated();
if (lastFocusOwner != null) {
lastFocusOwner.requestFocus();
} else {
Component defaultFocusOwner = defaultFocusOwner();
if (defaultFocusOwner != null) defaultFocusOwner.requestFocus();
}
KeyboardFocusManager.getCurrentKeyboardFocusManager().
addPropertyChangeListener("focusOwner", focusListener); // NOI18N
}
private void updateItemPresenters() {
if (pieChart.getModel().getItemCount() != itemPresenters.size()) {
repopulateItemPresenters();
updateSnippets();
} else {
refreshItemPresenters();
}
Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if ((focusOwner != null) && !focusOwner.isShowing()) {
navPanel.requestFocusInWindow();
}
}
public JEyeDropperDemo() {
super(true, true, false);
exampleLabel.setVisible(false);
Inspector layout = new Inspector(configurationPanel);
layout.addRow(new JLabel("Diameter:"), diameterSpinner);
layout.addRow(new JLabel("Magnification:"), magSpinner);
layout.addRow(new JLabel("Color:"), colorWell);
layout.addRow(showEyeDropper, false);
showEyeDropper.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// wait for the button to fully
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// we need the eyedropper to capture the correct
// image,
// so we need to:
// step 1: remove the focus ring
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.clearGlobalFocusOwner();
// step 2: repaint immediately
showEyeDropper.paintImmediately(0, 0,
showEyeDropper.getWidth(),
showEyeDropper.getHeight());
showEyeDropper();
}
});
}
});
colorWell.getColorSelectionModel().setSelectedColor(Color.black);
colorWell.setEnabled(false);
}
public Map getContext() {
HashMap result = new HashMap();
result.put (getClass(), this);
if (isModified()) {
result.put ("save", Boolean.TRUE);
result.put ("modified", Boolean.TRUE);
}
if (isNewFile()) {
result.put ("isNewFile", Boolean.TRUE);
}
if (canUndo()) {
result.put ("undo", Boolean.TRUE);
}
if (canRedo()) {
result.put ("redo", Boolean.TRUE);
}
result.put ("doc", Boolean.TRUE);
Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
if (documentTabs.isAncestorOf(owner)) {
if (canPaste()) {
result.put ("clipboardcontents", clipboard);
}
if (hasSelection()) {
result.put ("selection", Boolean.TRUE);
}
}
return result;
}
protected boolean isFocused( Component c ) {
if( c instanceof JScrollPane ) {
JViewport viewport = ((JScrollPane)c).getViewport();
Component view = (viewport != null) ? viewport.getView() : null;
if( view != null ) {
if( FlatUIUtils.isPermanentFocusOwner( view ) )
return true;
if( (view instanceof JTable && ((JTable)view).isEditing()) ||
(view instanceof JTree && ((JTree)view).isEditing()) )
{
Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
if( focusOwner != null )
return SwingUtilities.isDescendingFrom( focusOwner, view );
}
}
return false;
} else if( c instanceof JComboBox && ((JComboBox<?>)c).isEditable() ) {
Component editorComponent = ((JComboBox<?>)c).getEditor().getEditorComponent();
return (editorComponent != null) ? FlatUIUtils.isPermanentFocusOwner( editorComponent ) : false;
} else if( c instanceof JSpinner ) {
if( FlatUIUtils.isPermanentFocusOwner( c ) )
return true;
JComponent editor = ((JSpinner)c).getEditor();
if( editor instanceof JSpinner.DefaultEditor ) {
JTextField textField = ((JSpinner.DefaultEditor)editor).getTextField();
if( textField != null )
return FlatUIUtils.isPermanentFocusOwner( textField );
}
return false;
} else
return FlatUIUtils.isPermanentFocusOwner( c );
}
private static void runTest2() throws Exception {
hitKey(robot, KeyEvent.VK_TAB);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() != btnEnd) {
System.out.println("Non Grouped Radio Button Go To Next Component through Tab Key failed");
throw new RuntimeException("Focus is not on Button End as Expected");
}
}
});
}
void removeItems() {
if (lastFocused != null) {
if(!lastFocused.requestFocusInWindow()) {
// Workarounr for 4810575.
// If lastFocused is not in currently focused window
// requestFocusInWindow will fail. In this case we must
// request focus by requestFocus() if it was not
// transferred from our popup.
Window cfw = KeyboardFocusManager
.getCurrentKeyboardFocusManager()
.getFocusedWindow();
if(cfw != null &&
"###focusableSwingPopup###".equals(cfw.getName())) {
lastFocused.requestFocus();
}
}
lastFocused = null;
}
if (invokerRootPane != null) {
invokerRootPane.removeKeyListener(this);
invokerRootPane.setFocusTraversalKeysEnabled(focusTraversalKeysEnabled);
removeUIInputMap(invokerRootPane, menuInputMap);
removeUIActionMap(invokerRootPane, menuActionMap);
invokerRootPane = null;
}
receivedKeyPressed = false;
}
/**
* Add keyboard listener to the dialog window.
*/
private void addKeyboardListener() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher((KeyEvent e) -> {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ESCAPE) {
dispose();
}
return false;
});
}
public void init() {
robot = Util.createRobot();
kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent event) {
System.out.println("--> " + event);
}
}, FocusEvent.FOCUS_EVENT_MASK | WindowEvent.WINDOW_FOCUS_EVENT_MASK);
}
private void doReturn() {
KeyboardFocusManager fmgr =
KeyboardFocusManager.getCurrentKeyboardFocusManager();
Component focusOwner = fmgr.getFocusOwner();
if(focusOwner != null && !(focusOwner instanceof JRootPane)) {
return;
}
MenuSelectionManager msm = MenuSelectionManager.defaultManager();
MenuElement path[] = msm.getSelectedPath();
MenuElement lastElement;
if(path.length > 0) {
lastElement = path[path.length-1];
if(lastElement instanceof JMenu) {
MenuElement newPath[] = new MenuElement[path.length+1];
System.arraycopy(path,0,newPath,0,path.length);
newPath[path.length] = ((JMenu)lastElement).getPopupMenu();
msm.setSelectedPath(newPath);
} else if(lastElement instanceof JMenuItem) {
JMenuItem mi = (JMenuItem)lastElement;
if (mi.getUI() instanceof BasicMenuItemUI) {
((BasicMenuItemUI)mi.getUI()).doClick(msm);
}
else {
msm.clearSelectedPath();
mi.doClick(0);
}
}
}
}
void removeItems() {
if (lastFocused != null) {
if(!lastFocused.requestFocusInWindow()) {
// Workarounr for 4810575.
// If lastFocused is not in currently focused window
// requestFocusInWindow will fail. In this case we must
// request focus by requestFocus() if it was not
// transferred from our popup.
Window cfw = KeyboardFocusManager
.getCurrentKeyboardFocusManager()
.getFocusedWindow();
if(cfw != null &&
"###focusableSwingPopup###".equals(cfw.getName())) {
lastFocused.requestFocus();
}
}
lastFocused = null;
}
if (invokerRootPane != null) {
invokerRootPane.removeKeyListener(this);
invokerRootPane.setFocusTraversalKeysEnabled(focusTraversalKeysEnabled);
removeUIInputMap(invokerRootPane, menuInputMap);
removeUIActionMap(invokerRootPane, menuActionMap);
invokerRootPane = null;
}
receivedKeyPressed = false;
}
public static void main(String[] args) throws InterruptedException, java.lang.reflect.InvocationTargetException
{
final Frame frame = new Frame("the test");
frame.setLayout(new FlowLayout());
final Button btn1 = new Button("button 1");
frame.add(btn1);
frame.add(new Button("button 2"));
frame.add(new Button("button 3"));
frame.pack();
frame.setVisible(true);
Robot r = Util.createRobot();
Util.waitForIdle(r);
Util.clickOnComp(btn1, r);
Util.waitForIdle(r);
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
if (kfm.getFocusOwner() != btn1) {
throw new RuntimeException("test error: can not set focus on " + btn1 + ".");
}
EventQueue.invokeAndWait(new Runnable() {
public void run() {
final int n_comps = frame.getComponentCount();
for (int i = 0; i < n_comps; ++i) {
frame.getComponent(i).setVisible(false);
}
}
});
Util.waitForIdle(r);
final Component focus_owner = kfm.getFocusOwner();
if (focus_owner != null && !focus_owner.isVisible()) {
throw new RuntimeException("we have invisible focus owner");
}
System.out.println("test passed");
frame.dispose();
}
@Override
public void install(JPopover<T> popover) {
PopoverHierarchyBoundsListener l1 = hierarchyBoundsListenerMap
.get(popover);
if (l1 == null) {
l1 = new PopoverHierarchyBoundsListener(popover);
hierarchyBoundsListenerMap.put(popover, l1);
popover.getOwner().addHierarchyBoundsListener(l1);
}
PopoverHierarchyListener l2 = hierarchyListenerMap.get(popover);
if (l2 == null) {
l2 = new PopoverHierarchyListener(popover);
hierarchyListenerMap.put(popover, l2);
popover.getOwner().addHierarchyListener(l2);
}
PopoverComponentListener l3 = componentListenerMap.get(popover);
if (l3 == null) {
l3 = new PopoverComponentListener(popover);
componentListenerMap.put(popover, l3);
popover.getOwner().addComponentListener(l3);
}
PopoverPropertyChangeListener l4 = propertyListenerMap.get(popover);
if (l4 == null) {
l4 = new PopoverPropertyChangeListener(popover);
propertyListenerMap.put(popover, l4);
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addPropertyChangeListener(PROPERTY_ACTIVE_WINDOW, l4);
}
}
private static void runTest6() throws Exception {
hitKey(robot, KeyEvent.VK_UP);
hitKey(robot, KeyEvent.VK_UP);
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() != radioBtn2) {
System.out.println("Radio button Group Circle Back To First Button Test");
throw new RuntimeException("Focus is not on Radio Button B as Expected");
}
}
});
}