Can't focus JScrollPane?
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() {}
开发者_StackOverflow
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);
I think that not possible to set the Focus to the JScrolPane, but set Focus to the JComponent, which is place into JScrolPane couldn't be problem
Runnable doRun = new Runnable() {
@Override
public void run() {
myComponent.requestFocus();//requestFocusInWindow
myComponent.grabFocus();
}
};
SwingUtilities.invokeLater(doRun);
Why do you need this? I think you should set focus on the component inside the JScrollPane. How do you detect that the focus isn't there? Scrollpane itself has no visible part (may be just 1 pixel frame is visible).
As noted in How to Use Key Bindings: How Key Bindings Work, composite components typically use the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
map. You can even add bindings to the top-level component's root pane, as shown in Key Bindings.
I've no clue what the problem was; for lack of a better idea I deleted and retyped everything, and now it works. It is possible to focus a JScrollPane, in case anyone reading this wishes to. I assumed it was possible, since by default both .isFocusable() and isRequestFocusEnabled() are set to true. But yeah, I have no idea; at the very least I got a few good links for key binding. Thanks for the help!
精彩评论