Skip to content

Instantly share code, notes, and snippets.

@seanf
Last active November 17, 2021 01:35
Show Gist options
  • Save seanf/15a9274176172234b0b4f59529b449f3 to your computer and use it in GitHub Desktop.
Save seanf/15a9274176172234b0b4f59529b449f3 to your computer and use it in GitHub Desktop.
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