Last active
November 17, 2021 01:35
-
-
Save seanf/15a9274176172234b0b4f59529b449f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.jetbrains.annotations.NotNull; | |
import org.jetbrains.annotations.Nullable; | |
import javax.swing.*; | |
import javax.swing.event.DocumentEvent; | |
import javax.swing.event.DocumentListener; | |
import javax.swing.text.JTextComponent; | |
import java.awt.*; | |
import java.awt.event.*; | |
import java.util.function.Consumer; | |
public class SwingFocusHelper { | |
/** | |
* Calls JComponent.requestFocusInWindow(), but uses console logging for the result, | |
* and logs component diagostics if it fails. | |
* @see JComponent#requestFocusInWindow() | |
*/ | |
public static boolean requestFocusInWindow(JComponent component, String name) { | |
var result = component.requestFocusInWindow(); | |
SenseiInternalMode.ifInternalMode(() -> { | |
printf("requestFocusInWindow for %s returned %s\n", name, result); | |
if (!result) { | |
printf(" The following may explain why:\n" + | |
" The component must be displayable, focusable, visible and all of its\n" + | |
" ancestors (with the exception of the top-level Window) must be visible for the\n" + | |
" [requestFocusInWindow] request to be granted.\n"); | |
logComponentFocusState(component, name); | |
} | |
}); | |
return result; | |
} | |
private static void logComponentFocusState(JComponent c, String name) { | |
printf(" - component %s isDisplayable:%s isFocusable:%s isVisible:%s\n", | |
name, c.isDisplayable(), c.isFocusable(), c.isVisible()); | |
logComponentFamilyVisibility(c.getParent()); | |
} | |
private static void logComponentFamilyVisibility(@Nullable Container c) { | |
if (c != null) { | |
printf(" - parent of type %s isVisible:%s\n", | |
c.getClass().getName(), c.isVisible()); | |
logComponentFamilyVisibility(c.getParent()); | |
} | |
} | |
private static void printf(String format, Object... params) { | |
System.err.printf(format, params); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment