I'm having issues giving focus to a JScrollPane. I'm trying to do this when the window is created so that I can try out the key bindings I'm working on. Everything shows up where it's supposed to be and at the correct size. What I've got looks like this:
import java.awt.*;
import java.swing.*;
public class MyInterface extends JFrame {
public MyInterface() {}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
// define custom table model
JTable table = new JTable(model);
MyScrollPane scrollPane = new MyScrollPane(table);
MyInterface frame = new MyInterface();
scrollPane.setPreferredSize(new Dimension(512, 512));
frame.getContentPane().add(scrollPane);
frame.pack();
frame.setVisible();
scrollPane.requestFocus();
}
}
public class MyScrollPane extends JScrollPane implements KeyListener {
public MyScrollPane(Component view) {
super(view, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
}
// key event processing
}
I tried adding a window listener to the frame which would request focus for scrollPane after the window was finished opening, but it didn't help. Any ideas?
EDIT: Thought I should mention that scrollPane.isFocusable() and scrollPane.isRequestFocusEnabled both return true, so I should be able to give it focus.
EDIT: It seems I'm unable to give focus to anything (frame, table, etc.), so there's some other problem here. No matter what I try, this displays null:
Component compFocusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
System.out.println("focus owner: " + compFocusOwner);